package org.gcube.execution.ocrservice.tests;

import java.io.FileInputStream;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.execution.ocrservice.utils.CMUtils;
import org.gcube.contentmanagement.contentmanager.stubs.CollectionReference;
import org.gcube.contentmanagement.gcubedocumentlibrary.io.DocumentWriter;



/* Use this client to upload ocropus.tar.gz.gz in a scope 
 * This is a backup plan in the case in which we can't find a SL5 node with ocropus installed in scope so we will have to get it from CMS
 */
public class UploadOcropusClient {

	public static void main(String args[]) {

		if(args.length!=2){
			System.out.println("Usage:    java org.gcube.execution.ocrservice.tests.UploadOcropusClient <GCUBE scope>   <path of ocropus.tar.gz");
			System.out.println("Example:  java org.gcube.execution.ocrservice.tests.UploadOcropusClient /gcube/devNext $GLOBUS_LOCATION/Ocropus/Ocropus-1.0.0.tar.gz");
			System.exit(1);
		}

		try{
			System.out.println("Scope:                  " + args[0]);
			System.out.println("Ocropus file to upload: " + args[1]);
			System.out.println("");
			
			GCUBEScope scope = GCUBEScope.getScope(args[0]);

			///---> delete all "ocrOcropusCollection" collections in scope
			System.out.println("Going to delete all collections with name='"+ CMUtils.ocrOcropusCollectionPrefix + "_" + args[0]);
			CMUtils.deleteAllOCROcropusCollections(scope);
			
			CollectionReference ocropusCollectionReference = null;			
			//we create the collection now
			System.out.println("We will create ocrOcropusCollection now in scope " + scope );
			ocropusCollectionReference = CMUtils.createOCROcropusCollection(scope);
			if(ocropusCollectionReference==null){
				System.out.println("Could not create collection.");
				System.exit(1);
			}

			System.out.println("Created ocropus collection with id: " + ocropusCollectionReference.getCollectionID() + " scope:" + scope );

			//get writer on the new collection
			DocumentWriter	writer = CMUtils.getDocumentWriterByCollectionReference( ocropusCollectionReference, scope);

			//read the ocropus file from argument[1]
			System.out.println("Reading 1 file of ocropus.tar.gz.gz" + args[1]);
			FileInputStream ocropusFile = new FileInputStream( args[1] );

			//write the document with ocropus-0.3.1-i386-JK.tar.gz.gz and get CM Reference
			System.out.println("Creating ocropus document ");
			String cmRef = CMUtils.createOCRDocument(writer, "ocropus.tar.gz.gz" , ocropusFile, scope);
			System.out.println("Stored in CMS with ref: " + "cms://"+ocropusCollectionReference.getCollectionID()+"/"+ cmRef );

		}catch(Exception ex){
			ex.printStackTrace();
		}
		
	}

}