package ISClient;

import java.util.Iterator;
import java.util.List;

import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.informationsystem.client.ISClient;
import org.gcube.common.core.informationsystem.client.RPDocument;
import org.gcube.common.core.informationsystem.client.queries.GCUBEGHNQuery;
import org.gcube.common.core.informationsystem.client.queries.GCUBERIQuery;
import org.gcube.common.core.informationsystem.client.queries.WSResourceQuery;
import org.gcube.common.core.resources.GCUBEHostingNode;
import org.gcube.common.core.resources.GCUBERunningInstance;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.security.GCUBESecurityManagerImpl;

public class RetrieveResourcesStats {

	public static void main(String[] args) throws Exception{
		GCUBESecurityManagerImpl managerSec = new GCUBESecurityManagerImpl() {  public boolean isSecurityEnabled() {return false;}};
		
		GCUBEScope scope = GCUBEScope.getScope(args[0]);
		
		System.out.println(args[0]);
		
		ISClient client = GHNContext.getImplementation(ISClient.class);

		GCUBEGHNQuery ghnQuery = client.getQuery(GCUBEGHNQuery.class);

		//get the GHNs from IS
		List<GCUBEHostingNode> list =  client.execute(ghnQuery, scope);
		Iterator<GCUBEHostingNode> iter = list.iterator();
		while(iter.hasNext())
		{
			GCUBEHostingNode current = iter.next(); 
			String ghnID = current.getID();
			System.out.println("GHN: " + current.getNodeDescription().getName() + " with ID: " + ghnID + " has RIs:");
			
			//get the RIs for this GHN
			GCUBERIQuery riQuery = client.getQuery(GCUBERIQuery.class);
			
			String filter = "($result//child::*[local-name()='GHN' and @UniqueID='"+ ghnID +"'])";
			
			riQuery.addGenericCondition(filter);
			
			//System.out.println(riQuery.getExpression());
			
			List<GCUBERunningInstance> RIlist = client.execute(riQuery, scope);
			
			Iterator<GCUBERunningInstance> RIiter = RIlist.iterator();
			
			int count = 0;
			
			while(RIiter.hasNext())
			{
				GCUBERunningInstance currentRI = RIiter.next(); 
				String riID = currentRI.getID();
				
				System.out.println("RI of: " + currentRI.getServiceClass() + "/" + currentRI.getServiceName() + " with ID: " + riID + " has published WS resources:");
				
				//get the WS-resources for this RI
				WSResourceQuery wsQuery = client.getQuery(WSResourceQuery.class);
				
				String filterWS = "($result//child::*[local-name()='RI']/text() eq '"+riID+"')";
				// + " and ($outer//child::*[local-name()='GHN']/text() eq '"+ghnID+"')";
				
				wsQuery.addGenericCondition(filterWS);
				
				//System.out.println(wsQuery.getExpression());
				
				List<RPDocument> WSlist = client.execute(wsQuery, scope);
				
				System.out.println(WSlist.size());
				
				count += WSlist.size();
				
			}
			System.out.println("GHN total:");
			System.out.println(count);
		}
		System.out.println();
		
	}

	
}
