package it.cnr.isti.driver.utils;

import java.rmi.RemoteException;

import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.driver.www.wsdl.is_lookup_wsdl.IS_LookUpStub;
import org.driver.www.wsdl.is_lookup_wsdl.IS_LookUpStub.GetResourceProfileByQuery;

public class IS_LookUpClient {

	protected Log log = LogFactory.getLog(IS_LookUpClient.class);

	IS_LookUpStub lookup = null;

	private int retries = 1;

	public IS_LookUpClient() {
	}

	public IS_LookUpClient(String address) {
		setAddress(address);
	}

	public void setAddress(String address) {
		log.debug("Setting LookUp address: " + address);
		try {
			lookup = new IS_LookUpStub(address);
		} catch (AxisFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String[] quickSearchProfile(String query) {
		log.debug("executing xquery on IS");
		IS_LookUpStub.QuickSearchProfile sp = new IS_LookUpStub.QuickSearchProfile();

		sp.setXQuery(query);
		for (int i = 0; i < retries; i++) {
			try {
				IS_LookUpStub.QuickSearchProfileResponse sr = lookup.quickSearchProfile(sp);
				IS_LookUpStub.Array1 quickResult = sr.getReturn();
				return quickResult.getElement();
			} catch (RemoteException e) {
				log.debug("retrying quick search profile: " + i);
			}
		}
		throw new IllegalStateException("problem communicating with IS service");

	}

	public String getResourceProfileByQuery(String query) {
		log.debug("executing singe xquery on IS");

		GetResourceProfileByQuery sp = new GetResourceProfileByQuery();

		sp.setXQuery(query);

		for (int i = 0; i < retries; i++) {
			try {
				return lookup.getResourceProfileByQuery(sp).getReturn();
			} catch (RemoteException e) {
				log.debug("retrying get resource profile by query: " + i);
			}
		}
		throw new IllegalStateException("problem communicating with IS service");
	}

	public int getRetries() {
		return retries;
	}

	public void setRetries(int retries) {
		this.retries = retries;
	}
}
