/*
 * MIT License
 *
 * Copyright (c) 2018-2019 Daniel Cortes
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package danielcortes.xyz.models.documentos;

import danielcortes.xyz.data.ConnectionHolder;
import danielcortes.xyz.data.DAOManager;
import danielcortes.xyz.data.SQLiteConnectionHolder;
import danielcortes.xyz.models.caja.Caja;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SQLiteDocumentosDAO implements DocumentosDAO {
  private static final Logger log = LogManager.getLogger(SQLiteDocumentosDAO.class);
  private ConnectionHolder connectionHolder;

  public SQLiteDocumentosDAO() {
    this.connectionHolder = new SQLiteConnectionHolder();
  }

  public SQLiteDocumentosDAO(ConnectionHolder connectionHolder) {
    this.connectionHolder = connectionHolder;
  }

  @Override
  public List<Documentos> getAll() {
    log.debug("Se intentaran conseguir todos los Documentos");
    List<Documentos> documentosList = new ArrayList<>();
    String query = "select * from documentos";
    try (Connection conn = connectionHolder.getConnection()) {
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        try (ResultSet rs = ps.executeQuery()) {
          while (rs.next()) {
            //Confio en que la base de datos mapeo correctamente la caja_id
            @SuppressWarnings("OptionalGetWithoutIsPresent")
            Caja caja = DAOManager.getCajaDAO().getById(rs.getInt("caja_id")).get();

            Documentos documentos = new Documentos();
            documentos.setCaja(caja);
            documentos.setId(rs.getInt("id"));
            documentos.setCheques(rs.getInt("cheques"));
            documentos.setTarjetas(rs.getInt("tarjetas"));
            documentos.setRetiros(rs.getInt("retiros"));

            documentosList.add(documentos);
          }
        }
      }
    } catch (SQLException e) {
      log.error("Error al intentar conseguir todos los Documentos de la base de datos", e);
    }
    log.debug("Se consiguieron " + documentosList.size() + " Documentos");
    return documentosList;
  }

  @Override
  public Optional<Documentos> getById(int id) {
    log.debug("Se intentara conseguir el Documentos con id " + id);
    Documentos documentos = null;

    try (Connection conn = connectionHolder.getConnection()) {
      String query = "select * from documentos where id = ?";
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        ps.setInt(1, id);
        try (ResultSet rs = ps.executeQuery()) {
          if (rs.next()) {
            //Confio en que la base de datos mapeo correctamente la caja_id
            @SuppressWarnings("OptionalGetWithoutIsPresent")
            Caja caja = DAOManager.getCajaDAO().getById(rs.getInt("caja_id")).get();

            documentos = new Documentos();
            documentos.setCaja(caja);
            documentos.setId(rs.getInt("id"));
            documentos.setCheques(rs.getInt("cheques"));
            documentos.setTarjetas(rs.getInt("tarjetas"));
            documentos.setRetiros(rs.getInt("retiros"));
          }
        }
      }
    } catch (SQLException e) {
      log.error("Error al intentar conseguir el Documentos con id " + id, e);
    }
    log.debug("Se consiguio el Documentos " + documentos);
    return Optional.ofNullable(documentos);
  }

  @Override
  public Optional<Documentos> getByCaja(Caja caja) {
    log.debug("Se intentara conseguir el Documentos de la caja " + caja);
    Documentos documentos = null;

    if (Caja.EMPTY == caja) {
      log.debug("La caja entregada era Caja.EMPTY");
      return Optional.ofNullable(documentos);
    }

    String query = "select * from documentos where caja_id = ?";
    try (Connection conn = connectionHolder.getConnection()) {
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        ps.setInt(1, caja.getId());
        try (ResultSet rs = ps.executeQuery()) {
          if (rs.next()) {
            documentos = new Documentos();
            documentos.setCaja(caja);
            documentos.setId(rs.getInt("id"));
            documentos.setCheques(rs.getInt("cheques"));
            documentos.setTarjetas(rs.getInt("tarjetas"));
            documentos.setRetiros(rs.getInt("retiros"));
          }
        }
      }
    } catch (SQLException e) {
      log.error("Error al intentar conseguir el documentos de la caja " + caja, e);
    }

    log.debug("Se consiguio el Documentos " + documentos);
    return Optional.ofNullable(documentos);
  }

  @Override
  public int getTotalDocumentos(Caja caja) {
    log.debug("Se intentara conseguir el total de Documentos de la caja " + caja);
    int total = 0;
    if (Caja.EMPTY == caja) {
      log.debug("La caja entregada era Caja.EMPTY");
      return total;
    }

    String query = "select cheques + tarjetas + retiros from documentos where caja_id = ?";
    try (Connection conn = connectionHolder.getConnection()) {
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        ps.setInt(1, caja.getId());
        try (ResultSet rs = ps.executeQuery()) {
          if (rs.next()) {
            total = rs.getInt(1);
          }
        }
      }
    } catch (SQLException e) {
      log.error("Error al intentar conseguir la suma de los documentos de la caja " + caja);
    }
    log.debug("La suma obtenida es "  + total);
    return total;
  }

  @Override
  public void insert(Documentos documentos) {
    log.debug("Se intentara insertar un nuevo documentos " + documentos);
    String query = "insert into documentos (cheques, tarjetas, retiros, caja_id) values (?,?,?,?)";
    try (Connection conn = connectionHolder.getConnection()) {
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        ps.setInt(1, documentos.getCheques());
        ps.setInt(2, documentos.getTarjetas());
        ps.setInt(3, documentos.getRetiros());
        ps.setInt(4, documentos.getCaja().getId());
        ps.executeUpdate();
      }

      try (PreparedStatement ps = conn.prepareStatement("select last_insert_rowid()")) {
        try (ResultSet rs = ps.executeQuery()) {
          rs.next();
          documentos.setId(rs.getInt(1));
        }
      }

    } catch (SQLException e) {
      log.error("Error al intentar insertar el documentos " + documentos);
    }
    log.debug("Se inserto el documentos " + documentos);
  }

  @Override
  public void update(Documentos documentos) {
    log.debug("Se intentara actualizar el documentos " + documentos);
    String query = "update documentos set tarjetas = ?, cheques = ?, retiros = ?, caja_id = ? where id = ?";
    try (Connection conn = connectionHolder.getConnection()) {
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        ps.setInt(1, documentos.getTarjetas());
        ps.setInt(2, documentos.getCheques());
        ps.setInt(3, documentos.getRetiros());
        ps.setInt(4, documentos.getCaja().getId());
        ps.setInt(5, documentos.getId());
        ps.executeUpdate();
      }
    } catch (SQLException e) {
      log.error("Error al actualizar el documentos " + documentos, e);
    }
    log.debug("Se actualizo el documentos " + documentos);
  }

  @Override
  public void delete(Documentos documentos) {
    log.debug("Se intentara eliminar el documentos " + documentos);
    String query = "delete from documentos where id = ?";
    try (Connection conn = connectionHolder.getConnection()) {
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        ps.setInt(1, documentos.getId());
        ps.execute();
      }
    } catch (SQLException e) {
      log.error("Error al eliminar el documentos " + documentos, e);
    }
    log.debug("Se elimino el documentos " + documentos);
  }
}
