/*
 * 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.
 */
package eu.dnetlib.espas.spatial.utils;

import eu.dnetlib.espas.spatial.TimePeriodConstraint;
import eu.dnetlib.espas.spatial.impl.TimePeriodCalculator;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.logging.Level;
import org.apache.log4j.Logger;
import org.joda.time.Period;

/**
 *
 * @author gathanas
 */
public class SatDataFileUtils {
   private static final Logger _logger = Logger.getLogger(SatDataFileUtils.class);
   
   
   public SatDataFileUtils() {
   }
 
   public synchronized void generateEpochFile(File ouputFile, TimePeriodCalculator timeCalculator, TimePeriodConstraint timeConstraint) throws IOException{
      
      FileWriter epochFileWriter = new FileWriter(ouputFile);
      Period constraintPeriod = timeCalculator.estimatePeriod(timeConstraint);
      List<Date[]> timePeriodPoints = timeCalculator.findPeriodicTimestamps(timeConstraint.getFromDate(), timeConstraint.getToDate(), constraintPeriod);
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
      dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
      
      for(Date[] datePoints:timePeriodPoints)
         epochFileWriter.write(dateFormat.format(datePoints[1])+"\n");
      
      epochFileWriter.flush();
      epochFileWriter.close();
   }
   
   public Map<String,String> getSatNameLocationFileMap(File satListFile) throws FileNotFoundException{
      Map<String,String> satList  = new HashMap<String,String>();
      FileReader satFReader = new FileReader(satListFile);
      LineNumberReader lineReader = new LineNumberReader(satFReader);
      boolean moreLinesToRead = true;

      do{
         try {
            String lineCont = lineReader.readLine();
            if(lineCont!=null){
            String[] lineParts =lineCont.split(",");
            if(lineParts.length>3)
              satList.put(lineParts[2].trim(),lineParts[2].trim()+"."+lineParts[3].trim());
            }
            else
               moreLinesToRead=false;
         } catch (IOException ex) {
            _logger.error("Failed to read line from satellite location file "+satListFile.getPath(), ex);
            moreLinesToRead=false;
         }
      }while(moreLinesToRead);

      return satList;
   }
      
   public synchronized Map<Date,String> getSatLocationXMLRecords(File satLocationFile) throws FileNotFoundException{
      Map<Date,String> gmlNodesList  = new HashMap<Date,String>();
      FileReader sateLocationFReader = new FileReader(satLocationFile);
      LineNumberReader lineReader = new LineNumberReader(sateLocationFReader);
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
      dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
      boolean moreLinesToRead = true;
      do{
         try {
            String lineCont = lineReader.readLine();
            if(lineCont!=null){
            String[] lineParts =lineCont.split(",");
            if(lineParts.length>=4)
              gmlNodesList.put(dateFormat.parse(lineParts[0]),"<gml:Point xmlns:gml=\"http://www.opengis.net/gml/3.2\" srsName=\"http://ontology.espas-fp7.eu/crs/GEOspherical\" srsDimension=\"3\"><gml:pos>"+
                 lineParts[1].trim()+" "+lineParts[2].trim()+" "+(Double.valueOf(lineParts[3].trim())*1000)+"</gml:pos></gml:Point>");
            }
            else
               moreLinesToRead=false;
         } catch (IOException ex) {
            _logger.error("Failed to read line from satellite location file "+satLocationFile.getPath(), ex);
            moreLinesToRead=false;
         } catch (ParseException ex) {
              _logger.error("Failed to parse date in satellite location", ex);
          }
      }while(moreLinesToRead);
      
    return gmlNodesList;
   }
}
