/*
 * 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.SQLiteConnectionHolder;
import danielcortes.xyz.models.documentos.Documentos;
import danielcortes.xyz.models.documentos.DocumentosDAO;
import danielcortes.xyz.models.documentos.SQLiteDocumentosDAO;
import danielcortes.xyz.models.efectivo.Efectivo;
import danielcortes.xyz.models.efectivo.EfectivoDAO;
import danielcortes.xyz.models.efectivo.SQLiteEfectivoDAO;

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.logging.Level;
import java.util.logging.Logger;

public class SQLiteCajaDAO extends CajaDAO {
    private static final Logger LOGGER = Logger.getLogger(SQLiteCajaDAO.class.getName());

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

    @Override
    public List<Caja> findAll() {
        List<Caja> cajaList = new ArrayList<>();
        try (Connection conn = connectionHolder.getConnection()) {
            String query = "select * from caja";
            PreparedStatement ps = conn.prepareStatement(query);
            ResultSet rs = ps.executeQuery();

            LOGGER.log(Level.FINE, "QUERY: {0}", new Object[]{query});

            cajaList = this.cajasFromResultSet(rs);

            rs.close();
            ps.close();
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, e.toString(), e);
        }

        return cajaList;
    }

    @Override
    public Caja findById(int id) {
        Caja caja = null;
        try (Connection conn = connectionHolder.getConnection()) {
            String query = "select * from caja where id = ?";
            PreparedStatement ps = conn.prepareStatement(query);
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();

            LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id});

            caja = this.cajasFromResultSet(rs).get(0);

            rs.close();
            ps.close();
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, e.toString(), e);
        }
        return caja;
    }

    @Override
    public Caja findByFecha(LocalDate fecha) {
        Caja caja = null;
        try (Connection conn = connectionHolder.getConnection()) {
            String query = "select * from caja where fecha = ?";

            PreparedStatement ps = conn.prepareStatement(query);
            ps.setString(1, fecha.toString());
            ResultSet rs = ps.executeQuery();

            LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, fecha});

            List<Caja> cajaList = this.cajasFromResultSet(rs);

            if (cajaList.size() > 0) {
                caja = cajaList.get(0);
            }

            rs.close();
            ps.close();
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, e.toString(), e);
        }
        return caja;
    }

    @Override
    public boolean insertCaja(Caja caja) {
        int updates;
        try (Connection conn = connectionHolder.getConnection()) {
            String query = "insert into caja (fecha) values (?)";
            PreparedStatement ps = conn.prepareStatement(query);
            ps.setString(1, caja.getFecha().toString());
            updates = ps.executeUpdate();

            LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}", new Object[]{query, caja.getFecha(), updates});

            ps.close();


            query = "select last_insert_rowid()";
            ps = conn.prepareStatement("select last_insert_rowid()");
            ResultSet rs = ps.executeQuery();

            LOGGER.log(Level.FINE, "QUERY: {0}", new Object[]{query});

            rs.next();
            caja.setId(rs.getInt(1));

            rs.close();
            ps.close();
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, e.toString(), e);
            return false;
        }
        return updates > 0;
    }

    @Override
    public boolean updateCaja(Caja caja) {
        int updates;
        try (Connection conn = connectionHolder.getConnection()) {
            String query = "update caja set fecha = ? where id = ?";
            PreparedStatement ps = conn.prepareStatement(query);
            ps.setString(1, caja.getFecha().toString());
            ps.setInt(2, caja.getId());
            updates = ps.executeUpdate();

            LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2} | updates: {3}]", new Object[]{query, caja.getFecha(), caja.getId(), updates});


            ps.close();
        }  catch (SQLException e) {
            LOGGER.log(Level.SEVERE, e.toString(), e);
            return false;
        }
        return updates > 0;
    }

    @Override
    public void createCajasForMonth(LocalDate month) {
        LocalDate date = month.withDayOfMonth(1);
        LocalDate endDate = date.withDayOfMonth(date.lengthOfMonth()).plusDays(1);
        int count = 0;

        LOGGER.log(Level.FINE, "Se intentara crear las cajas no existentes para las fechas entre {0} y {1}", new Object[]{date, endDate});

        while (date.isBefore(endDate)) {
            if (this.findByFecha(date) != null) {
                date = date.plusDays(1);
                continue;
            }

            Caja caja = new Caja();
            caja.setFecha(date);
            this.insertCaja(caja);

            Efectivo efectivo = new Efectivo();
            EfectivoDAO efectivoDAO = new SQLiteEfectivoDAO();
            efectivo.setCaja(caja);
            efectivoDAO.insertDefaultEfectivo(efectivo);

            Documentos documentos = new Documentos();
            DocumentosDAO documentosDAO = new SQLiteDocumentosDAO();
            documentos.setCaja(caja);
            documentosDAO.insertDefaultDocumentos(documentos);

            date = date.plusDays(1);
            count++;
        }

        LOGGER.log(Level.FINE, "Terminado de intentar crear las cajas y se crearon {2}", new Object[]{date, endDate, count});
    }
}
