package eu.dnetlib.data.sts;

import static org.junit.Assert.assertNotNull;

import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.wsaddressing.W3CEndpointReference;

import org.junit.Before;
import org.junit.Test;

import pl.edu.icm.driver.factories.UniBiBeansFactory;
import pl.edu.icm.driver.is.ISConstants;
import pl.edu.icm.driver.is.ISUtils;
import eu.dnetlib.data.sts.das.IDataAccessService;
import eu.dnetlib.data.sts.ds.DepotServiceHelper;
import eu.dnetlib.data.sts.ds.IDepotService;
import eu.dnetlib.data.sts.ds.StorageConstants;
import eu.dnetlib.enabling.resultset.rmi.ResultSetService;

/**
 * Storage initializer class.
 * Useful when performing performance tests.
 * @author mhorst
 *
 */
public class StorageInitializer {

	String textTxtLocation = "http://212.87.15.77:28080/tester/resources/text_engine/sample_txt_document_en.txt";
	String depotServiceLocation = "http://212.87.15.112:8285/dnet-sts-ds/services/DepotService";
	String dataAccessServiceLocation = "http://212.87.15.112:8285/dnet-sts-das/services/DataAccessService";
	
	IDepotService depotService = null;
	IDataAccessService dataAccessService = null;
	
	private static final String TEST_OBJECT_ID_PREFIX = "test_id_";
	
	String globalStId = "6bf2161e-cb4a-4366-8d4a-125ffa131f17_U3RvcmVEU1Jlc291cmNlcy9TdG9yZURTUmVzb3VyY2VUeXBl";
	
	@Before
	public void init() {
		UniBiBeansFactory factory = new UniBiBeansFactory();
		depotService = factory.getDepot(depotServiceLocation);
		dataAccessService = factory.getDAS(dataAccessServiceLocation);
	}
	
//	@Test
	public void testInitialize() throws Exception {
//		String stId = depotService.createStore(null, StorageConstants.DEFAULT_MAX_ST_DS_SIZE);
		String stId = globalStId;
		System.out.println("stId: " + stId);
		
		List<String> data = new ArrayList<String>();
//		String uriObjectId1 = TEST_OBJECT_ID_PREFIX+System.currentTimeMillis();
		String uriObjectId1 = null;
		System.out.println("uriObjectId1: " + uriObjectId1);
//		data.add(DepotServiceHelper.buildStoreRecord(uriObjectId1, 
//				StorageConstants.STORE_DATATYPE_URI, textTxtLocation));
		data.add(DepotServiceHelper.buildStoreRecord(uriObjectId1, 
				StorageConstants.STORE_DATATYPE_DATA, "this is some data"));
//		String uriObjectId2 = TEST_OBJECT_ID_PREFIX+(System.currentTimeMillis()+10);
		String uriObjectId2 = null;
		System.out.println("uriObjectId2: " + uriObjectId2);
//		data.add(DepotServiceHelper.buildStoreRecord(uriObjectId2, 
//				StorageConstants.STORE_DATATYPE_URI, textTxtLocation));
		data.add(DepotServiceHelper.buildStoreRecord(uriObjectId2, 
				StorageConstants.STORE_DATATYPE_DATA, "this is some other data"));
		String actionId = depotService.storeObjects(
				stId, data, StorageConstants.STORING_TYPE_REFRESH);
		System.out.println("actionId: " + actionId);
		
//		Thread.sleep(2000);
//		System.out.println("object1 SDO: " + dataAccessService.getObjectSDO(
//				uriObjectId1, stId));
//		System.out.println("object2 SDO: " + dataAccessService.getObjectSDO(
//				uriObjectId2, stId));
		
	}
	
	@Test
	public void testCleanupStore() throws Exception {
		int packageSize = 100;
		W3CEndpointReference epr = dataAccessService.storeLookUpSDORS(globalStId);
		assertNotNull(epr);
		ResultSetService resultSetService = epr.getPort(ResultSetService.class);
		assertNotNull(resultSetService);
		String rsId = ISUtils.extractResultSetId(epr);
		assertNotNull(rsId);
		int totalSize = resultSetService.getNumberOfElements(rsId);
		System.out.println("rs total size: " + totalSize);
		if (totalSize==0) {
			System.out.println("no records to be deleted!");
			return;
		}
		boolean hasMore = true;
		int startElement = 1;
		while(hasMore) {
			int endElement = (startElement+packageSize<totalSize)?startElement+packageSize:totalSize;
			List<String> res = resultSetService.getResult(rsId, 
					startElement, endElement, 
					ISConstants.RESULT_SET_REQUEST_MODE_WAITING);
			List<String> toBeDeletedIds = new ArrayList<String>();
			for (String currentRes : res) {
				toBeDeletedIds.add(
						extractObjectId(currentRes));
			}
			System.out.println("deleting package: [" + startElement + "-" + endElement + "]");
			for (String curToDel : toBeDeletedIds) {
				System.out.println("to be del: " + curToDel);
			}
			depotService.deleteStoreObject(globalStId, toBeDeletedIds);
			if (endElement<totalSize) {
				startElement = endElement+1;
			} else {
				hasMore = false;
			}
		}
	}
	
//	@Test
	public void testDeleteStore() throws Exception {
		depotService.deleteStore(globalStId);
	}
	
//	@Test
	public void testTmp() throws Exception {
		String sdoProfile = "<RESOURCE_PROFILE><HEADER><RESOURCE_IDENTIFIER value=\"test_id_1258546432351\"/><RESOURCE_TYPE value=\"SimpleDigitalObjectDSResourceType\"/><RESOURCE_KIND value=\"StoreDSResources\"/><RESOURCE_URI value=\"http://localhost:9285/yadda-server/descriptor\"/><DATE_OF_CREATION value=\"2009-11-18T12:15:18+00:00\"/></HEADER><BODY><CONFIGURATION><SDO_MIME_TYPE>text/plain</SDO_MIME_TYPE></CONFIGURATION><STATUS><LAST_MODIFICATION_DATE></LAST_MODIFICATION_DATE><SDO_SIZE>0</SDO_SIZE><SDO_VERSION/><SDO_URI>http://212.87.15.112:9285/yadda-server/part/c95cd135-3d02-4a15-99d9-09e990aa5d64_U3RvcmVEU1Jlc291cmNlcy9TdG9yZURTUmVzb3VyY2VUeXBl/objects/test_id_1258546432351?type=BasicContent</SDO_URI><SDO/></STATUS></BODY></RESOURCE_PROFILE>";
		System.out.println(extractObjectId(sdoProfile));
	}
	
	protected String extractObjectId(String sdoProfile) throws Exception {
//		this is very lame method, but it is working in this particular scenario;
		String expectedPart = "RESOURCE_IDENTIFIER value=\"";
		int startIdIdx = sdoProfile.indexOf(expectedPart);
		if (startIdIdx>0) {
			String sdoSplitted = sdoProfile.substring(startIdIdx + expectedPart.length());
			return sdoSplitted.substring(0, sdoSplitted.indexOf("\""));
		} else {
			throw new Exception("couldn't find id in sdoProfile: " + sdoProfile);
		}
	}
	
}
