/*
 * 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.caja;

import danielcortes.xyz.data.ConnectionHolder;
import danielcortes.xyz.data.SQLiteConnectionHolder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
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 SQLiteCajaDAO implements CajaDAO {
  private static final Logger log = LogManager.getLogger(SQLiteCajaDAO.class);
  private ConnectionHolder connectionHolder;

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

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

  @Override
  public List<Caja> getAll() {
    log.debug("Se intentara conseguir todas las Cajas");
    List<Caja> cajaList = new ArrayList<>();
    try (Connection conn = connectionHolder.getConnection()) {
      String query = "select * from caja";
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        try (ResultSet rs = ps.executeQuery()) {
          while (rs.next()) {
            Caja caja = new Caja();
            caja.setId(rs.getInt("id"));
            caja.setFecha(LocalDate.parse(rs.getString("fecha")));
            caja.setFondo(rs.getInt("fondo"));
            cajaList.add(caja);
          }
        }
      }
    } catch (SQLException e) {
      log.error("Error al intentar obtener todas las Cajas", e);
    }
    log.debug("Se encontraron " + cajaList.size() + " cajas");
    return cajaList;
  }

  @Override
  public Optional<Caja> getById(int id) {
    log.debug("Se intentara conseguir una Caja con el id " + id);
    Caja caja = null;
    String query = "select * from caja where id = ?";
    try (Connection conn = connectionHolder.getConnection()) {
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        ps.setInt(1, id);
        try (ResultSet rs = ps.executeQuery()) {
          while (rs.next()) {
            caja = new Caja();
            caja.setId(rs.getInt("id"));
            caja.setFecha(LocalDate.parse(rs.getString("fecha")));
            caja.setFondo(rs.getInt("fondo"));
          }
        }
      }
    } catch (SQLException e) {
      log.error("Error al intentar conseguir la caja con id " + id, e);
    }
    log.debug("La caja que se consigio es " + caja);
    return Optional.ofNullable(caja);
  }

  @Override
  public Optional<Caja> getByFecha(LocalDate fecha) {
    log.debug("Se intentara conseguir la caja con fecha " + fecha);
    Caja caja = null;
    String query = "select * from caja where fecha = ?";
    try (Connection conn = connectionHolder.getConnection()) {
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        ps.setString(1, fecha.toString());
        try (ResultSet rs = ps.executeQuery()) {
          while (rs.next()) {
            caja = new Caja();
            caja.setId(rs.getInt("id"));
            caja.setFecha(LocalDate.parse(rs.getString("fecha")));
            caja.setFondo(rs.getInt("fondo"));
          }
        }
      }
    } catch (SQLException e) {
      log.error("Error al intentar conseguir la caja con fecha " + fecha, e);
    }
    log.debug("Se consiguio la caja " + caja);
    return Optional.ofNullable(caja);
  }

  @Override
  public void insert(Caja caja) {
    log.debug("Se intentara insertar la caja " + caja);

    if(caja == Caja.EMPTY){
      log.debug("La caja era Caja.EMPTY, no se puede insertar");
      return;
    }

    String query = "insert into caja (fecha, fondo) values (?, ?)";
    try (Connection conn = connectionHolder.getConnection()) {
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        ps.setString(1, caja.getFecha().toString());
        ps.setInt(2, caja.getFondo());
        ps.executeUpdate();
      }

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

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

  @Override
  public void update(Caja caja) {
    log.debug("Se intentara actualizar la caja " + caja);
    String query = "update caja set fecha = ?, fondo = ? where id = ?";
    try (Connection conn = connectionHolder.getConnection()) {
      try (PreparedStatement ps = conn.prepareStatement(query)) {
        ps.setString(1, caja.getFecha().toString());
        ps.setInt(2, caja.getFondo());
        ps.setInt(3, caja.getId());
        ps.executeUpdate();
      }
    } catch (SQLException e) {
      log.error("Error al intentar actualizar la caja " + caja, e);
    }
    log.debug("Se actualizo la caja " + caja);
  }
}
