/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
GR4401100490000004951534330
 */

package eu.dnetlib.espas.sos.client;

import eu.dnetlib.espas.pep.AuthenticationPEP;
import eu.dnetlib.espas.sos.client.utils.DiskUtils;
import eu.dnetlib.espas.sos.client.utils.QuotaMonitor;
import eu.dnetlib.espas.sos.client.utils.SOSDBUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.postgresql.ds.PGPoolingDataSource;
import org.springframework.core.io.UrlResource;

/**
 *
 * @author gathanas
 */
public class SOSRequestManagerTest {
   
   List<String> observationIds;
   List<String> propertyIds;
   SOSDBUtils dBUtils;
   QuotaMonitor quotaMonitor;
   AuthenticationPEP pepAuth;
   
   Properties springConfProps = new Properties();
   
   public SOSRequestManagerTest() {
   }
   
   @Before
   public void setUp() throws IOException, Exception {
      PGPoolingDataSource dataSource = new PGPoolingDataSource();
      dataSource.setDatabaseName("dnet_espas");
      dataSource.setServerName("194.177.192.218");
      dataSource.setUser("dnet");
      dataSource.setPassword("dnetPwd");
      
      InputStream propsStream = SOSRequestManagerTest.class.getResourceAsStream("applicationContext-espas-sos-client.properties");
      springConfProps.load(propsStream);
      dBUtils = new SOSDBUtils();
      dBUtils.setSosDBSource(dataSource);
      dBUtils.init();
      
      DiskUtils diskUtils = new DiskUtils();
      diskUtils.setStorePath(new File("/tmp/sos"));
      diskUtils.init();
      
      quotaMonitor = new QuotaMonitor();
      quotaMonitor.setSosDBUtils(dBUtils);
      quotaMonitor.setDmSpaceUtils(diskUtils);
      quotaMonitor.setCleanupMillisecPeriod(180000);
      quotaMonitor.setRequestDownloadQuota("10mb");
      quotaMonitor.setServerDownloadQuota("10gb");
      
      observationIds = Arrays.asList("http://resources.espas-fp7.eu/observation/noa/fplotsM3000F2-Athens_20111201_20120603/1",
              "http://resources.espas-fp7.eu/observation/noa/fplotsM3000F2-Athens_201211010000_201212240000/1",
              "http://resources.espas-fp7.eu/observation/noa/AT138_201211280330_201211281615/1",
              "http://resources.espas-fp7.eu/observation/noa/AT138_201212161930_201212171215/1",
              "http://resources.espas-fp7.eu/observation/noa/AT138_201101140830_201101311000/1"/*,
              "http://resources.espas-fp7.eu/observation/noa/AthensIonogram_201304161615_201304170930/1",
              "http://resources.espas-fp7.eu/observation/noa/AthensIonogram_201305141730_201305141915/1",
              "http://resources.espas-fp7.eu/observation/noa/AT138_201304030815_201304031700/1",
              "http://resources.espas-fp7.eu/observation/noa/AT138_201302251330_201302252230/1",
              "http://resources.espas-fp7.eu/observation/noa/AthensIonogram_201212312130_201301101445/1",
              "http://resources.espas-fp7.eu/observation/noa/AthensIonogram_201303090043_201303090043/1",
              "http://resources.espas-fp7.eu/observation/noa/AT138_201211070745_201211172015/1",
              "http://resources.espas-fp7.eu/observation/noa/AT138_201303191515_201303191745/1",
              "http://resources.espas-fp7.eu/observation/noa/AthensIonogram_201304070300_201304081500/1",
              "http://resources.espas-fp7.eu/observation/noa/AthensIonogram_201305080515_201305080800/1",
              "http://resources.espas-fp7.eu/observation/noa/AthensIonogram_201301172000_201301172045/1",
              "http://resources.espas-fp7.eu/observation/noa/AthensIonogram_201305130730_201305140745/1",
              "http://resources.espas-fp7.eu/observation/noa/AthensIonogram_201302172245_201302251300/1",
              "http://resources.espas-fp7.eu/observation/noa/AT138_201305282315_201305312345/1",
              "http://resources.espas-fp7.eu/observation/noa/AT138_201302151345_201302171430/1",
              "http://resources.espas-fp7.eu/observation/noa/AT138_201212071145_201212080930/1",
              "http://resources.espas-fp7.eu/observation/noa/AT138_201303040645_201303060800/1"*/

//              ucl content
//              "http://resources.espas-fp7.eu/observation/ucl/fpi-g13320/1",
//              "http://resources.espas-fp7.eu/observation/ucl/fpi-g13319/1",
//              "http://resources.espas-fp7.eu/observation/ucl/fpi-g13318/1"
      );
      
      propertyIds = Arrays.asList(
              "http://ontology.espas-fp7.eu/compositeObservedProperty/noa-sao",
              "http://ontology.espas-fp7.eu/observedProperty/CriticalFrequency_F1-Layer",
              "http://ontology.espas-fp7.eu/observedProperty/M_3000km_F2-Layer", 
              "http://ontology.espas-fp7.eu/observedProperty/CriticalFrequency_F2-Layer", 
              "http://ontology.espas-fp7.eu/observedProperty/MinimumVirtualHeight_F2-Layer", 
              "http://ontology.espas-fp7.eu/observedProperty/MinimumFrequency_FirstHop_AllLayers", 
              "http://ontology.espas-fp7.eu/observedProperty/NeutralWindVelocity_Horizontal"/*, 
              "http://ontology.espas-fp7.eu/observedProperty/PhotonFlux_Optical"*/);
           
            pepAuth = new AuthenticationPEP();
            URL storeLocation = SOSRequestManagerTest.class.getClassLoader().getResource("wso2carbon.jks");
            pepAuth.setServerUrl("https://194.177.192.218:9443/services/EntitlementService");
            pepAuth.setServerUsername("espas_user");
            pepAuth.setServerPassword("espasPwd");
            pepAuth.setTrustStore(new UrlResource(storeLocation));
            pepAuth.setTrustStorePassword("wso2carbon");
            pepAuth.initEntitlementService();
   }

   /**
    * Test of submitDataRequest method, of class SOSRequestManager.
    */
   @Test
   public void testSubmitDataRequest() {
      try {
         System.out.println("submitDataRequest");
         
         List<TimePeriodConstraint> timePeriodConstraints = new LinkedList();
         TimePeriodConstraint tCon = new TimePeriodConstraint();
         SimpleDateFormat dtFormater = new SimpleDateFormat("dd-MM-yyyy");
         tCon.setFromDate(dtFormater.parse("01-11-2012"));
         tCon.setToDate(dtFormater.parse("20-12-2012"));
         timePeriodConstraints.add(tCon);
         
         SOSRequestInfo requestInfo = new SOSRequestInfo(observationIds, propertyIds, timePeriodConstraints);
         
         String userId = "stefania.martziou@gmail.com";
         SOSRequestManager instance = new SOSRequestManager();
         instance.setQuotaMonitor(quotaMonitor);
         instance.setDbSourceUtils(dBUtils);
         instance.setAuthenticationPEP(pepAuth);
         instance.setPoolThreadSize(Integer.parseInt(springConfProps.get("sos.client.pool.size").toString()));
         instance.setSosStoreLocation(springConfProps.getProperty("sos.client.store.location"));
         instance.setClearTempRequestResponses(Boolean.FALSE);
         instance.setAscii_csvXSLT(new UrlResource(this.getClass().getResource("ascii_csv.xsl")));
         instance.setSosXSLT(new UrlResource(this.getClass().getResource("sos.xsl")));
//         instance.setSossweXSLT(new UrlResource(this.getClass().getResource("sos_swe.xsl")));
         instance.init();

         String requestId = instance.submitDataRequest(requestInfo, userId, null);
          SOSRequestStatus.RequestStatus status = instance.getDataRequestStatus(requestId, userId).getStatus();
         while(status!=SOSRequestStatus.RequestStatus.COMPLETED && 
                 status!=SOSRequestStatus.RequestStatus.FAILED
                 )
             Thread.sleep(1000);
             
         assertNotNull(requestId);
      } catch (Exception ex) {
         Logger.getLogger(SOSRequestManagerTest.class).error(null, ex);
      }
   }

   /**
    * Test of getDataRequestStatus method, of class SOSRequestManager.
    */
//   @Test
   public void testGetDataRequestStatus() {
      System.out.println("getDataRequestStatus");
      String requestId = "SOSReqID--986694154";
      String userId = "stefania.martziou@gmail.com";
      SOSRequestManager instance = new SOSRequestManager();
      instance.setDbSourceUtils(dBUtils);
      instance.setPoolThreadSize(Integer.parseInt(springConfProps.get("sos.client.pool.size").toString()));
      instance.setSosStoreLocation(springConfProps.getProperty("sos.client.store.location"));
      instance.init();
      SOSRequestStatus result = instance.getDataRequestStatus(requestId, userId);
      Logger.getLogger(SOSRequestManagerTest.class).info("Request status is :"+result.getStatus().name()+" and message is :"+result.getDescription()+". Expiration time :"+result.getExpirationDate().toString());
      assertNotNull(result);
      // TODO review the generated test code and remove the default call to fail.
   }

   /**
    * Test of getDataRequestResponseStream method, of class SOSRequestManager.
    */
//   @Test
   public void testGetDataRequestResponseStream() throws Exception {
      System.out.println("getDataRequestResponseStream");
      String requestId = "SOSReqID-894391708";
      String userId = "stefania.martziou@gmail.com";
      SOSRequestManager instance = new SOSRequestManager();
      instance.setDbSourceUtils(dBUtils);
      instance.setPoolThreadSize(Integer.parseInt(springConfProps.get("sos.client.pool.size").toString()));
      instance.setSosStoreLocation(springConfProps.getProperty("sos.client.store.location"));
      instance.init();
      InputStream result = instance.getDataRequestResponseStream(requestId, userId);
      IOUtils.copy(result, System.out);
      assertNotNull(result);
      // TODO review the generated test code and remove the default call to fail.
   }

   /**
    * Test of getResponseStreamIn method, of class SOSRequestManager.
    */
//   @Test
   public void testGetResponseStreamIn() throws Exception {
      System.out.println("getResponseStreamIn");
      String requestId = "SOSReqID--1271507457";
      String userId = "stefania.martziou@gmail.com";
      SOSRequestManager instance = new SOSRequestManager();
      dBUtils.init();
      instance.setDbSourceUtils(dBUtils);
      instance.setPoolThreadSize(Integer.parseInt(springConfProps.get("sos.client.pool.size").toString()));
      instance.setSosStoreLocation(springConfProps.getProperty("sos.client.store.location"));
      instance.init();
      InputStream result = instance.getResponseStreamIn(requestId, "ascii_csv", userId);
      IOUtils.copy(result, System.out);
      assertNotNull(result);
      // TODO review the generated test code and remove the default call to fail.
   }

   /**
    * Test of getSupportedXSLTStream method, of class SOSRequestManager.
    */
//   @Test
   public void testGetSupportedXSLTStream() throws IOException {
      System.out.println("getSupportedXSLTStream");
      String name = "ascii_csv";
      String requestId = "SOSReqID-894391708";
      String userId = "stefania.martziou@gmail.com";
      SOSRequestManager instance = new SOSRequestManager();
      instance.setDbSourceUtils(dBUtils);
      instance.setXsltMapFileLocation(SOSRequestManagerTest.class.getResource("xsltmappings.properties").toString().replace("file:", ""));
      instance.setPoolThreadSize(Integer.parseInt(springConfProps.get("sos.client.pool.size").toString()));
      instance.setSosStoreLocation(springConfProps.getProperty("sos.client.store.location"));
      instance.init();
      InputStream result = instance.getSupportedXSLTStream(name);
      IOUtils.copy(result, System.out);
      assertNotNull(result);
   }

   /**
    * Test of getSupportedTransformations method, of class SOSRequestManager.
    */
//   @Test
   public void testGetSupportedTransformations() {
      System.out.println("\ngetSupportedTransformations");
      String requestId = "SOSReqID-894391708";
      String userId = "stefania.martziou@gmail.com";
      SOSRequestManager instance = new SOSRequestManager();
      instance.setDbSourceUtils(dBUtils);
      instance.setPoolThreadSize(Integer.parseInt(springConfProps.get("sos.client.pool.size").toString()));
      instance.setSosStoreLocation(springConfProps.getProperty("sos.client.store.location"));
      instance.setXsltMapFileLocation(SOSRequestManagerTest.class.getResource("xsltmappings.properties").toString().replace("file:", ""));
      instance.init();
      Collection<String> result = instance.getSupportedTransformations();
      for(String key: result)
         System.out.println("XSLT rule name is :"+key);
      assertNotNull(result);
   }

//      @Test
   public void tetsTransformResponseIn() throws IOException, InterruptedException {
      System.out.println("\ngetResponseStreamIn");
      String requestId = "SOSReqID-922716067";
      String userId = "stefania.martziou@gmail.com";
      SOSRequestManager instance = new SOSRequestManager();
      instance.setDbSourceUtils(dBUtils);
      instance.setPoolThreadSize(Integer.parseInt(springConfProps.get("sos.client.pool.size").toString()));
      instance.setSosStoreLocation(springConfProps.getProperty("sos.client.store.location"));
      instance.init();
      InputStream resultStream = instance.getResponseStreamIn(requestId, "ascii_csv", userId);
      
      IOUtils.copy(resultStream ,System.out);
   }

//   @Test
   public void testOGCSOService(){
       try{
         List<TimePeriodConstraint> timePeriodConstraints = new LinkedList();
         TimePeriodConstraint tCon = new TimePeriodConstraint();
         SimpleDateFormat dtFormater = new SimpleDateFormat("dd-MM-yyyy");
         tCon.setFromDate(dtFormater.parse("01-01-2011"));
         tCon.setToDate(dtFormater.parse("20-01-2011"));
         timePeriodConstraints.add(tCon);

         SOSRequestInfo requestInfo = new SOSRequestInfo(observationIds, propertyIds, timePeriodConstraints);
         
         String userId = "stefania.martziou@gmail.com";
         SOSRequestManager instance = new SOSRequestManager();
         instance.setQuotaMonitor(quotaMonitor);
         instance.setDbSourceUtils(dBUtils);
         instance.setAuthenticationPEP(pepAuth);
         instance.setPoolThreadSize(Integer.parseInt(springConfProps.get("sos.client.pool.size").toString()));
         instance.setSosStoreLocation(springConfProps.getProperty("sos.client.store.location"));
         instance.setClearTempRequestResponses(Boolean.FALSE);
         instance.setAscii_csvXSLT(new UrlResource(this.getClass().getResource("ascii_csv.xsl")));
         instance.setSosXSLT(new UrlResource(this.getClass().getResource("sos.xsl")));
         instance.setSossweXSLT(new UrlResource(this.getClass().getResource("sos_swe.xsl")));
         instance.init();
         
         SimpleDateFormat dtFormater2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

         
         String requestId = instance.submitRequest("http://resources.espas-fp7.eu/acquisition/ucl/uclSvalbardKHOobservatory-FPIgreen/1#In", "http://ontology.espas-fp7.eu/observedProperty/PhotonFlux_Optical", 
                 dtFormater2.parse("2008-10-18T05:47:13"), dtFormater2.parse("2008-12-18T06:47:13"), userId);
         
       }catch(Exception ex){
           Logger.getLogger(SOSRequestManagerTest.class.getCanonicalName()).log(Priority.ERROR, ex, ex);
       }
    }
}

