package br.com.elotech.websaude.integracao.esus.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import static br.com.elotech.websaude.integracao.esus.model.dao.Conexao.CONN;

public class EsusHistorico {

  protected static String sql = "";
  protected static PreparedStatement pstmt;
  private Timestamp dtInicial;
  private Timestamp dtFinal;

  public int initHistorico() throws SQLException {

    sql = "select nextval ('esus_exportacao_historico_eeh_codigo_seq')";
    int id = 0;
    pstmt = CONN.prepareStatement(sql);
    ResultSet rs = pstmt.executeQuery();
    if (rs.next()) {
      id = rs.getInt(1);
    }
    sql = "INSERT INTO esus_exportacao_historico (eeh_codigo,eeh_data_inicial) VALUES (?, now())";
    pstmt = CONN.prepareStatement(sql);
    pstmt.setInt(1, id);
    pstmt.execute();
    CONN.commit();
    return id;

  }

  public boolean endHistorico(int idHistorico) throws SQLException {
    sql = "UPDATE esus_exportacao_historico SET eeh_data_final = now() where eeh_codigo = ?";
    pstmt = CONN.prepareStatement(sql);
    pstmt.setInt(1, idHistorico);
    pstmt.executeUpdate();
    CONN.commit();
    return true;
  }

  public void gravaHistorico(int id) throws SQLException {
    sql = "UPDATE esus_exportacao_historico SET eeh_data_inicial = ? , eeh_data_final = ? WHERE eeh_codigo = ?";
    pstmt = CONN.prepareStatement(sql);
    pstmt.setTimestamp(1, dtInicial);
    pstmt.setTimestamp(2, dtFinal);
    pstmt.setInt(3, id);
    pstmt.executeUpdate();
    CONN.commit();
  }

  public Timestamp getDtInicial() {
    return dtInicial;
  }

  public void setDtInicial(Date dtInicial) {
    this.dtInicial = new Timestamp(dtInicial.getTime());
  }

  public Timestamp getDtFinal() {
    return dtFinal;
  }

  public void setDtFinal(Date dtFinal) {
    this.dtFinal = new Timestamp(dtFinal.getTime());
  }
}
