/*
 * 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 br.com.elotech.websaude.integracao.esus;

import br.com.elotech.websaude.integracao.esus.controller.DadosEsus;
import br.com.elotech.websaude.integracao.esus.model.dao.Conexao;
import org.apache.commons.io.comparator.LastModifiedFileComparator;

import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author elotech
 */
public class Main {
  public static void main(String[] args) {
    if (args.length == 3) {
      if (Conexao.abrirConexao(args)) {
        try {

          processar();
          varreServidorArqs();
          Conexao.CONN.commit();

        } catch (SQLException | IOException | JAXBException ex) {
          try {
            Conexao.CONN.rollback();
          } catch (SQLException ex1) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex1);
          }
          Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
          Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        Conexao.fecharConexao();
      }

    }
  }

  private static void processar() throws SQLException, IOException, JAXBException, ParseException {
    DadosEsus dadosEsus = new DadosEsus();
    dadosEsus.geraArquivo();
  }

  protected static void varreServidorArqs() {
    File directory = new File("arqs/");
    if (!directory.exists()) {
      directory.mkdir();
    }
    if (!directory.canWrite()) {
      try {
        throw new Exception("Não é possível escrever.");
      } catch (Exception ex) {
        Logger.getLogger(DadosEsus.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    File[] arqs = directory.listFiles();
    Arrays.sort(arqs, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
    for (File file : arqs) {

      Date ultModificado = new Date(file.lastModified());
      if (ultModificado
        .before(new Date(ultModificado.getYear(), ultModificado.getMonth() - 4, ultModificado.getDay()))) {
        if (file.canWrite()) {
          file.deleteOnExit();
        }
      }

      if (file.getName().contains("xml")) {
        file.deleteOnExit();
      }
    }
  }

}
