/**
 * Copyright 2009-2012 OpenAIRE PROJECT (Bielefeld University)
 * Original author: Marek Imialek <marek.imialek at uni-bielefeld.de>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.dnetlib.data.udm.client;

import java.util.List;

import javax.xml.ws.wsaddressing.W3CEndpointReference;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import eu.dnetlib.data.udm.IUsageDataMergingService;
import eu.dnetlib.data.udm.UsageDataMergingServiceException;
import eu.dnetlib.enabling.resultset.rmi.ResultSetException;
import eu.dnetlib.enabling.resultset.rmi.ResultSetService;
import eu.dnetlib.enabling.tools.JaxwsServiceResolverImpl;

import static org.junit.Assert.assertNotNull;

/**
 * The Class SimpleUDMClient is a simple client testing getAllRecords 
 * function. 
 * 
 * @author <a href="mailto:marek.imialek at uni-bielefeld.de">Marek Imialek</a>
 */
public class SimpleUDMClient {

	/** The service. */
	private static IUsageDataMergingService service;
	//private static String address = "http://localhost:8090/app/services/UsageDataMergingService?";
	/** The address. */
	private static String address = "http://129.70.40.104:8287/unibi-data-merging-service/services/UsageDataMergingService?";
	
	/**
	 * The main method.
	 * 
	 * @param args the args
	 * 
	 * @throws UsageDataMergingServiceException the usage data merging service exception
	 */
	public static void main(String[] args) throws UsageDataMergingServiceException {
		
		Logger  logger = Logger.getLogger("eu.dnetlib.data");
		logger.setLevel(Level.INFO);
		
		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		factory.setServiceClass(IUsageDataMergingService.class);
		factory.setAddress(address);
		service = (IUsageDataMergingService) factory.create();
		assertNotNull(service.identify(), "Can not connect UDM Service");
		System.out.println("Service Identify: " + service.identify() );
		
		W3CEndpointReference epr = service.getAllRecords("2011-01-02", "2011-03-28");
		System.out.println("EPR: " + epr);
		
		JaxwsServiceResolverImpl serviceResolver = new JaxwsServiceResolverImpl();	
		ResultSetService resultSetService = serviceResolver.getService(
				ResultSetService.class, epr);
		
		String rsId = serviceResolver.getResourceIdentifier(epr);
			
		try {	
			int recordsNumber = resultSetService.getNumberOfElements(rsId);
			System.out.println("Number of elements stored in RS:" + recordsNumber);
			
		} catch (ResultSetException e2) {
			String err = "Exception: Can not get" +
					" number of results from ResultSet :"+e2.getMessage();
			System.out.println(err);
			throw new UsageDataMergingServiceException(err);
		}

		if (rsId == null) {
			String errorContent = "Exception: Ignoring MDStore, the resultset identifier not "
				+ "extracted from EPR " + epr.toString();
			System.out.println(errorContent);
			throw new UsageDataMergingServiceException(errorContent);
		}
	
		System.out.println("Getting results from RS.");
		
		boolean dowhile = true;
		int resCounter = 0;
		int fromPosition = 1;
		int toPosition = 0;
		int harvestPackageSize = 50;
		
		while (dowhile) {
			try {	
				int recordsNumber = resultSetService.getNumberOfElements(rsId);
				String status = resultSetService.getRSStatus(rsId);
				System.out.println("Status: " + status);
				System.out.println("Number of elements stored in RS:" + recordsNumber);
				
				if (recordsNumber != 0 && recordsNumber != resCounter) {
					toPosition = fromPosition + harvestPackageSize - 1;
					
					if (toPosition > recordsNumber)
						toPosition = recordsNumber;
					
					System.out.println("Get for range: "+ fromPosition + " - " + toPosition);
					List<String> results = resultSetService.getResult(rsId, fromPosition, toPosition, "non-waiting");
			
					if (results == null)
						continue;
					resCounter += results.size();
					
					int resDiff = toPosition - fromPosition + 1;
					if (resDiff != results.size())
						fromPosition = resCounter + 1;
					else
						fromPosition = toPosition + 1;
					
					System.out.println("Got "+ resCounter +" records from RS");
				} else {
					System.out.println("Sleeping");
					Thread.sleep(1000);
				}
				
				if (recordsNumber == resCounter && "closed".equals(status))
					dowhile =false;
				
			} catch (ResultSetException e2) {
				String err = "Exception: Can not get" +
						" number of results from ResultSet :"+e2.getMessage();
				System.out.println(err);
				throw new UsageDataMergingServiceException(err);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		System.out.println("Loading from RS finished, got "+ resCounter+ " records.");
		
	}

}
