package examenes.examen20250321.controlador;

import examenes.examen20250321.modelo.Inquilino;
import examenes.examen20250321.modelo.Vivienda;

import java.sql.*;

public class ControladorInquilino {
    public static Inquilino obtenerInquilino(Vivienda v) {
        Connection conn = GestorConexiones.getConnection();

        try {
            PreparedStatement pt = conn.prepareStatement("select * from inquilino where idVivienda = ? limit 1;");
            pt.setInt(1, v.getId());

            ResultSet rs = pt.executeQuery();

            rs.next();

            return new Inquilino(
                    rs.getInt("id"),
                    rs.getString("dni"),
                    rs.getString("nombreCompleto"),
                    rs.getDate("fechaInicioAlquiler"),
                    rs.getDate("fechaFinAlquiler"),
                    rs.getFloat("cuotaMensual"),
                    rs.getInt("idVivienda"),
                    rs.getInt("idTipoMorosidad")
            );

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    public static int guardarInquilino(Inquilino i) {
        Connection conn = GestorConexiones.getConnection();

        try {
            PreparedStatement pt = conn.prepareStatement("update inquilino set " +
                    "dni = ?," +
                    "nombreCompleto = ?," +
                    "fechaInicioAlquiler = ?," +
                    "fechaFinAlquiler = ?," +
                    "cuotaMensual = ?," +
                    "idVivienda = ?," +
                    "idTipoMorosidad = ?" +
                    " where id = ?");

            pt.setString(1, i.getDni());
            pt.setString(2, i.getNombreCompleto());
            pt.setDate(3, new Date(i.getFechaInicioAlquiler().getTime()));
            if (i.getFechaFinAlquiler() != null) {
                pt.setDate(4, new Date(i.getFechaFinAlquiler().getTime()));
            } else pt.setDate(4, null);
            pt.setFloat(5, i.getCuotaMensual());
            pt.setInt(6, i.getIdVivienda());
            pt.setInt(7, i.getIdTipoMorosidad());
            pt.setInt(8, i.getId());

            return pt.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
