/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.kiwi.cometd.utils;

import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author esner
 */
public class ExternalDataLoader {
  final static Logger logger = LoggerFactory.getLogger(ExternalDataLoader.class);
  
  private static ExternalDataLoader externalDataLoaderInstance;
  
  public static ExternalDataLoader getInstance(){
        if (externalDataLoaderInstance == null) {
            externalDataLoaderInstance = new ExternalDataLoader();         
        }
        
        return externalDataLoaderInstance;
  }
  
  public String getUpdateTimestamp() {
      String timestampFileLocation;
      String timestamp = null;
      
      try {
          timestampFileLocation = KiwiResourceLoader.getInstance().getPropertyFromResource(CometdClientUtils.RESOURCE_NAME, CometdClientUtils.TIMESTAMP_LOCATION_KEY);
      }
      catch (IOException e) {
          logger.info("Cannot load timestamp file location!");
          return timestamp;
      }
      
      if (timestampFileLocation == null || timestampFileLocation.length() == 0)
          return timestamp;
      
       File file = new File(timestampFileLocation); 
       file.setReadOnly();

       try {
            FileInputStream fis = new FileInputStream(file);

            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fis);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            timestamp = br.readLine();
            // dispose all the resources after using them.
            fis.close();
            in.close();
            br.close();

        } catch (FileNotFoundException e) {
            logger.info("File timestamp not found!");
        } catch (IOException e) {
            logger.info("IO Exception: " + e.getCause());
        }
      
      return timestamp;
  }
}
