package ISClient;

import java.util.List;

import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.faults.GCUBERetrySameException;
import org.gcube.common.core.informationsystem.client.ISClient;
import org.gcube.common.core.informationsystem.client.QueryParameter;
import org.gcube.common.core.informationsystem.client.XMLResult;
import org.gcube.common.core.informationsystem.client.queries.GCUBEGenericQuery;
import org.gcube.common.core.resources.GCUBEGenericResource;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.opensearch.opensearchdatasource.ServiceContext;

/**
 * IS client which retrieves a generic resource
 * 
 * @author gerasimos.farantatos, NKUA
 *
 */
public class RetrieveGenericResource {

	public static int ISRETRY = 3;
	
	/**
	 * Prints client usage and exits
	 */
	public static void printUsageAndExit() {
		System.out.println("RetrieveGenericResource <scope> -id <GR_ID>");
		System.out.println("RetrieveGenericResource <scope> -name <GR_NAME>");
		System.exit(-1);
	}
	
	/**
	 * Queries the IS for a generic resource with a gived id and prints the retrieved resource serialization to standard output
	 * 
	 * @param args The arguments of the client
	 * @throws Exception In case of error
	 */
	public static void main(String[] args) throws Exception {
		
		if (args.length != 3) {
			System.out.println("Wrong number of arguments. Usage:");
			printUsageAndExit();
		}
		String queryEl = null;
		GCUBEScope scope = GCUBEScope.getScope(args[0]);
		if(args[1].compareTo("-id") == 0)
			queryEl = "ID";
		else if(args[1].compareTo("-name") == 0)
			queryEl = "Profile/Name";
		else
			printUsageAndExit();
		
		String attribute = args[2];
		ISClient client = null;
		GCUBEGenericQuery query = null;
	//	try{
			client =  GHNContext.getImplementation(ISClient.class);
			query = client.getQuery("GCUBEResourceQuery");
	//	}catch (Exception e) {
	//		throw new GCUBERetryEquivalentException("Could not get ISClient or GCUBEGenericQuery");
	//	}
		
		query.addParameters(new QueryParameter("FILTER", "$result/" + queryEl + "/string() eq '" + attribute + "'"),
				new QueryParameter("TYPE", GCUBEGenericResource.TYPE),
				new QueryParameter("RESULT", "$result/Profile/Body"));

		List<XMLResult> res = null;
		for(int retryOnError=0;retryOnError<ISRETRY;retryOnError+=1){
			try{
				res = client.execute(query, scope);
			}catch(Exception e){
				System.out.println("Could not retrieve generic resource. Retrying");
				e.printStackTrace();
				continue;
			}
			break;
		}
		
		if(res == null || res.size() == 0)
			System.out.println("The generic resource with " + (queryEl.compareTo("ID") == 0 ? "id " : "name ") + attribute + " was not found.");
		else if(res.size() > 1)
			System.out.println("The generic resource with : " + (queryEl.compareTo("ID") == 0 ? "id " : "name ") + attribute + " was found " + res.size() + " times published.");
		
		if(res != null && res.size() != 0)
			System.out.println(res.get(0).toString());
	}
}
