package tutorialJava.examenes.examen20250321.vista;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import tutorialJava.examenes.examen20250321.controlador.ControladorInquilino;
import tutorialJava.examenes.examen20250321.controlador.ControladorLocalidad;
import tutorialJava.examenes.examen20250321.controlador.ControladorTipoMorosidad;
import tutorialJava.examenes.examen20250321.controlador.ControladorVivienda;
import tutorialJava.examenes.examen20250321.modelo.Inquilino;
import tutorialJava.examenes.examen20250321.modelo.Localidad;
import tutorialJava.examenes.examen20250321.modelo.TipoMorosidad;
import tutorialJava.examenes.examen20250321.modelo.Vivienda;

import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.util.Date;
import java.util.List;

import javax.swing.JCheckBox;
import java.awt.Font;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.awt.event.ActionEvent;

public class GestionAlquileres extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private JTextField jtfId;
	private JTextField jtfDni;
	private JTextField jtfNombreInquilino;
	private JTextField jtfFechaInicio;
	private JTextField jtfFechaFin;
	private JTextField jtfCuotaMensual;
	private JTextField jtfFiltroVivienda;
	private JComboBox<Localidad> jcbLocalidad;
	private JComboBox<TipoMorosidad> jcbTipoMorosidad;
	private JComboBox<Vivienda> jcbVivienda;
	private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
	private JLabel jlblCuotaConIva;
	private JCheckBox chkActivo;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					GestionAlquileres frame = new GestionAlquileres();
					frame.pack();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public GestionAlquileres() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

		setContentPane(contentPane);
		GridBagLayout gbl_contentPane = new GridBagLayout();
		gbl_contentPane.columnWidths = new int[]{0, 0, 0, 0};
		gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
		gbl_contentPane.columnWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE};
		gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		contentPane.setLayout(gbl_contentPane);
		
		JLabel lblNewLabel = new JLabel("Gestión de alquileres");
		lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
		GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
		gbc_lblNewLabel.gridwidth = 3;
		gbc_lblNewLabel.insets = new Insets(15, 0, 5, 0);
		gbc_lblNewLabel.gridx = 0;
		gbc_lblNewLabel.gridy = 0;
		contentPane.add(lblNewLabel, gbc_lblNewLabel);
		
		JLabel lblNewLabel_1 = new JLabel("Localidad:");
		GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
		gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_1.gridx = 0;
		gbc_lblNewLabel_1.gridy = 1;
		contentPane.add(lblNewLabel_1, gbc_lblNewLabel_1);
		
		jcbLocalidad = new JComboBox();
		GridBagConstraints gbc_jcbLocalidad = new GridBagConstraints();
		gbc_jcbLocalidad.gridwidth = 2;
		gbc_jcbLocalidad.insets = new Insets(0, 0, 5, 0);
		gbc_jcbLocalidad.fill = GridBagConstraints.HORIZONTAL;
		gbc_jcbLocalidad.gridx = 1;
		gbc_jcbLocalidad.gridy = 1;
		contentPane.add(jcbLocalidad, gbc_jcbLocalidad);
		
		JLabel lblNewLabel_12 = new JLabel("Filtro de vivienda");
		GridBagConstraints gbc_lblNewLabel_12 = new GridBagConstraints();
		gbc_lblNewLabel_12.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_12.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_12.gridx = 0;
		gbc_lblNewLabel_12.gridy = 2;
		contentPane.add(lblNewLabel_12, gbc_lblNewLabel_12);
		
		jtfFiltroVivienda = new JTextField();
		GridBagConstraints gbc_jtfFiltroVivienda = new GridBagConstraints();
		gbc_jtfFiltroVivienda.insets = new Insets(0, 0, 5, 5);
		gbc_jtfFiltroVivienda.fill = GridBagConstraints.HORIZONTAL;
		gbc_jtfFiltroVivienda.gridx = 1;
		gbc_jtfFiltroVivienda.gridy = 2;
		contentPane.add(jtfFiltroVivienda, gbc_jtfFiltroVivienda);
		jtfFiltroVivienda.setColumns(10);
		
		JButton btnFiltroVivienda = new JButton("Filtrar viviendas");
		btnFiltroVivienda.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				filtrarViviendas();
			}
		});
		GridBagConstraints gbc_btnFiltroVivienda = new GridBagConstraints();
		gbc_btnFiltroVivienda.insets = new Insets(0, 0, 5, 0);
		gbc_btnFiltroVivienda.gridx = 2;
		gbc_btnFiltroVivienda.gridy = 2;
		contentPane.add(btnFiltroVivienda, gbc_btnFiltroVivienda);
		
		JLabel lblNewLabel_2 = new JLabel("Vivienda:");
		GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
		gbc_lblNewLabel_2.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_2.gridx = 0;
		gbc_lblNewLabel_2.gridy = 3;
		contentPane.add(lblNewLabel_2, gbc_lblNewLabel_2);
		
		jcbVivienda = new JComboBox();
		jcbVivienda.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cargarInquilino();
			}
		});
		GridBagConstraints gbc_jcbVivienda = new GridBagConstraints();
		gbc_jcbVivienda.gridwidth = 2;
		gbc_jcbVivienda.insets = new Insets(0, 0, 5, 0);
		gbc_jcbVivienda.fill = GridBagConstraints.HORIZONTAL;
		gbc_jcbVivienda.gridx = 1;
		gbc_jcbVivienda.gridy = 3;
		contentPane.add(jcbVivienda, gbc_jcbVivienda);
		
		JLabel lblNewLabel_3 = new JLabel("Datos del inquilino");
		lblNewLabel_3.setFont(new Font("Tahoma", Font.BOLD, 14));
		GridBagConstraints gbc_lblNewLabel_3 = new GridBagConstraints();
		gbc_lblNewLabel_3.gridwidth = 3;
		gbc_lblNewLabel_3.insets = new Insets(15, 0, 5, 0);
		gbc_lblNewLabel_3.gridx = 0;
		gbc_lblNewLabel_3.gridy = 4;
		contentPane.add(lblNewLabel_3, gbc_lblNewLabel_3);
		
		JLabel lblNewLabel_4 = new JLabel("Id:");
		GridBagConstraints gbc_lblNewLabel_4 = new GridBagConstraints();
		gbc_lblNewLabel_4.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_4.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_4.gridx = 0;
		gbc_lblNewLabel_4.gridy = 5;
		contentPane.add(lblNewLabel_4, gbc_lblNewLabel_4);
		
		jtfId = new JTextField();
		jtfId.setEnabled(false);
		GridBagConstraints gbc_jtfId = new GridBagConstraints();
		gbc_jtfId.gridwidth = 2;
		gbc_jtfId.insets = new Insets(0, 0, 5, 0);
		gbc_jtfId.fill = GridBagConstraints.HORIZONTAL;
		gbc_jtfId.gridx = 1;
		gbc_jtfId.gridy = 5;
		contentPane.add(jtfId, gbc_jtfId);
		jtfId.setColumns(10);
		
		JLabel lblNewLabel_5 = new JLabel("DNI:");
		GridBagConstraints gbc_lblNewLabel_5 = new GridBagConstraints();
		gbc_lblNewLabel_5.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_5.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_5.gridx = 0;
		gbc_lblNewLabel_5.gridy = 6;
		contentPane.add(lblNewLabel_5, gbc_lblNewLabel_5);
		
		jtfDni = new JTextField();
		GridBagConstraints gbc_jtfDni = new GridBagConstraints();
		gbc_jtfDni.gridwidth = 2;
		gbc_jtfDni.insets = new Insets(0, 0, 5, 0);
		gbc_jtfDni.fill = GridBagConstraints.HORIZONTAL;
		gbc_jtfDni.gridx = 1;
		gbc_jtfDni.gridy = 6;
		contentPane.add(jtfDni, gbc_jtfDni);
		jtfDni.setColumns(10);
		
		JLabel lblNewLabel_6 = new JLabel("Nombre completo:");
		GridBagConstraints gbc_lblNewLabel_6 = new GridBagConstraints();
		gbc_lblNewLabel_6.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_6.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_6.gridx = 0;
		gbc_lblNewLabel_6.gridy = 7;
		contentPane.add(lblNewLabel_6, gbc_lblNewLabel_6);
		
		jtfNombreInquilino = new JTextField();
		GridBagConstraints gbc_jtfNombreInquilino = new GridBagConstraints();
		gbc_jtfNombreInquilino.gridwidth = 2;
		gbc_jtfNombreInquilino.insets = new Insets(0, 0, 5, 0);
		gbc_jtfNombreInquilino.fill = GridBagConstraints.HORIZONTAL;
		gbc_jtfNombreInquilino.gridx = 1;
		gbc_jtfNombreInquilino.gridy = 7;
		contentPane.add(jtfNombreInquilino, gbc_jtfNombreInquilino);
		jtfNombreInquilino.setColumns(10);
		
		JLabel lblNewLabel_7 = new JLabel("Fecha inicio:");
		GridBagConstraints gbc_lblNewLabel_7 = new GridBagConstraints();
		gbc_lblNewLabel_7.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_7.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_7.gridx = 0;
		gbc_lblNewLabel_7.gridy = 8;
		contentPane.add(lblNewLabel_7, gbc_lblNewLabel_7);
		
		jtfFechaInicio = new JTextField();
		GridBagConstraints gbc_jtfFechaInicio = new GridBagConstraints();
		gbc_jtfFechaInicio.gridwidth = 2;
		gbc_jtfFechaInicio.insets = new Insets(0, 0, 5, 0);
		gbc_jtfFechaInicio.fill = GridBagConstraints.HORIZONTAL;
		gbc_jtfFechaInicio.gridx = 1;
		gbc_jtfFechaInicio.gridy = 8;
		contentPane.add(jtfFechaInicio, gbc_jtfFechaInicio);
		jtfFechaInicio.setColumns(10);
		
		chkActivo = new JCheckBox("Alquiler en activo");
		chkActivo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				checkAlquierActivo();
			}
		});
		GridBagConstraints gbc_chkActivo = new GridBagConstraints();
		gbc_chkActivo.gridwidth = 3;
		gbc_chkActivo.insets = new Insets(0, 0, 5, 0);
		gbc_chkActivo.gridx = 0;
		gbc_chkActivo.gridy = 9;
		contentPane.add(chkActivo, gbc_chkActivo);
		
		JLabel lblNewLabel_8 = new JLabel("Fecha de fin:");
		GridBagConstraints gbc_lblNewLabel_8 = new GridBagConstraints();
		gbc_lblNewLabel_8.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_8.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_8.fill = GridBagConstraints.VERTICAL;
		gbc_lblNewLabel_8.gridx = 0;
		gbc_lblNewLabel_8.gridy = 10;
		contentPane.add(lblNewLabel_8, gbc_lblNewLabel_8);
		
		jtfFechaFin = new JTextField();
		GridBagConstraints gbc_jtfFechaFin = new GridBagConstraints();
		gbc_jtfFechaFin.gridwidth = 2;
		gbc_jtfFechaFin.insets = new Insets(0, 0, 5, 0);
		gbc_jtfFechaFin.fill = GridBagConstraints.HORIZONTAL;
		gbc_jtfFechaFin.gridx = 1;
		gbc_jtfFechaFin.gridy = 10;
		contentPane.add(jtfFechaFin, gbc_jtfFechaFin);
		jtfFechaFin.setColumns(10);
		
		JLabel lblNewLabel_13 = new JLabel("Tipo de morosidad:");
		GridBagConstraints gbc_lblNewLabel_13 = new GridBagConstraints();
		gbc_lblNewLabel_13.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_13.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_13.gridx = 0;
		gbc_lblNewLabel_13.gridy = 11;
		contentPane.add(lblNewLabel_13, gbc_lblNewLabel_13);
		
		jcbTipoMorosidad = new JComboBox();
		GridBagConstraints gbc_jcbTipoMorosidad = new GridBagConstraints();
		gbc_jcbTipoMorosidad.gridwidth = 2;
		gbc_jcbTipoMorosidad.insets = new Insets(0, 0, 5, 5);
		gbc_jcbTipoMorosidad.fill = GridBagConstraints.HORIZONTAL;
		gbc_jcbTipoMorosidad.gridx = 1;
		gbc_jcbTipoMorosidad.gridy = 11;
		contentPane.add(jcbTipoMorosidad, gbc_jcbTipoMorosidad);
		
		JLabel lblNewLabel_9 = new JLabel("Cuota mensual (€):");
		GridBagConstraints gbc_lblNewLabel_9 = new GridBagConstraints();
		gbc_lblNewLabel_9.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_9.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_9.gridx = 0;
		gbc_lblNewLabel_9.gridy = 12;
		contentPane.add(lblNewLabel_9, gbc_lblNewLabel_9);
		
		jtfCuotaMensual = new JTextField();
		GridBagConstraints gbc_jtfCuotaMensual = new GridBagConstraints();
		gbc_jtfCuotaMensual.gridwidth = 2;
		gbc_jtfCuotaMensual.insets = new Insets(0, 0, 5, 0);
		gbc_jtfCuotaMensual.fill = GridBagConstraints.HORIZONTAL;
		gbc_jtfCuotaMensual.gridx = 1;
		gbc_jtfCuotaMensual.gridy = 12;
		contentPane.add(jtfCuotaMensual, gbc_jtfCuotaMensual);
		jtfCuotaMensual.setColumns(10);
		
		JLabel lblNewLabel_10 = new JLabel("Total mensual (IVA incluido) €:");
		GridBagConstraints gbc_lblNewLabel_10 = new GridBagConstraints();
		gbc_lblNewLabel_10.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_10.gridx = 0;
		gbc_lblNewLabel_10.gridy = 13;
		contentPane.add(lblNewLabel_10, gbc_lblNewLabel_10);
		
		jlblCuotaConIva = new JLabel("??? €");
		GridBagConstraints gbc_jlblCuotaConIva = new GridBagConstraints();
		gbc_jlblCuotaConIva.gridwidth = 2;
		gbc_jlblCuotaConIva.insets = new Insets(0, 0, 5, 0);
		gbc_jlblCuotaConIva.gridx = 1;
		gbc_jlblCuotaConIva.gridy = 13;
		contentPane.add(jlblCuotaConIva, gbc_jlblCuotaConIva);
		
		JButton btnGuardar = new JButton("Guardar cambios");
		btnGuardar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				guardarInquilino();
			}
		});
		GridBagConstraints gbc_btnGuardar = new GridBagConstraints();
		gbc_btnGuardar.gridwidth = 3;
		gbc_btnGuardar.gridx = 0;
		gbc_btnGuardar.gridy = 14;
		contentPane.add(btnGuardar, gbc_btnGuardar);
		
		// Carga de todas las localidades y tipos de morosidad
		cargarLocalidades();
		cargarTiposMorosidad();
	}

	/**
	 * 
	 */
	private void cargarLocalidades() {
		for(Localidad l : ControladorLocalidad.findAll()) {
			jcbLocalidad.addItem(l);
		}
	}
	
	
	/**
	 * 
	 */
	private void cargarTiposMorosidad() {
		for(TipoMorosidad l : ControladorTipoMorosidad.findAll()) {
			jcbTipoMorosidad.addItem(l);
		}
	}

	/**
	 * 
	 */
	private void filtrarViviendas() {
		Localidad localidadSeleccionada = 
				(Localidad) this.jcbLocalidad.getSelectedItem();
		int idLocalidadSeleccionada = localidadSeleccionada.getId();
		String filtroVivienda = this.jtfFiltroVivienda.getText();
		
		List<Vivienda> viviendas = ControladorVivienda
				.findAllByLocalidadAndFilterDescription(
						idLocalidadSeleccionada, filtroVivienda);
		
		this.jcbVivienda.removeAllItems();
		for (Vivienda v : viviendas) {
			this.jcbVivienda.addItem(v);
		}
	}
	
	/**
	 * 
	 */
	private void cargarInquilino() {
		if (jcbVivienda.getItemCount() > 0) {
			Vivienda viviendaSeleccionada = 
					(Vivienda) jcbVivienda.getSelectedItem();
			int idVivienda = viviendaSeleccionada.getId();
			
			Inquilino i = ControladorInquilino
					.findByIdVivienda(idVivienda);
			
			if (i != null) {
				this.jtfId.setText("" + i.getId());
				this.jtfDni.setText(i.getDni());
				this.jtfNombreInquilino.setText(i.getNombreCompleto());
				if (i.getFechaInicioAlquiler() != null) {
					this.jtfFechaInicio.setText(
							sdf.format(i.getFechaInicioAlquiler()));
				}
				else {
					this.jtfFechaInicio.setText("");
				}
				if (i.getFechaFinAlquiler() != null) {
					this.jtfFechaFin.setText(
							sdf.format(i.getFechaFinAlquiler()));
				}
				else {
					this.jtfFechaFin.setText("");
				}
				// Tipo de morosidad
				for(int j = 0; j < this.jcbTipoMorosidad.getItemCount(); j++) {
					if (this.jcbTipoMorosidad.getItemAt(j).getId() ==
							i.getIdTipoMorosidad()) {
						this.jcbTipoMorosidad.setSelectedIndex(j);
					}
				}
				// Cuota mensual
				this.jtfCuotaMensual.setText("" + i.getCuotaMensual());
				this.jlblCuotaConIva.setText("" + (i.getCuotaMensual() * 1.21));
			}
		}
	}
	
	/**
	 * 
	 */
	private void checkAlquierActivo() {
		if (chkActivo.isSelected()) {
			this.jtfFechaFin.setEnabled(false);
			this.jtfFechaFin.setText("");
		}
		else {
			this.jtfFechaFin.setEnabled(true);
		}
	}
	
	/**
	 * 
	 */
	private void guardarInquilino() {
		Inquilino i = new Inquilino();
		i.setId(Integer.parseInt(this.jtfId.getText()));
		i.setDni(this.jtfDni.getText());
		if (this.jtfNombreInquilino.getText().trim().equals("")) {
			JOptionPane.showMessageDialog(null, "Introduzca un nombre para el inquilino");
			return;
		}
		i.setNombreCompleto(this.jtfNombreInquilino.getText());
		Date fechaInicio = getFechaFromString(this.jtfFechaInicio.getText());
		if (!jtfFechaInicio.getText().trim().equals("") && 
				fechaInicio == null) {
			JOptionPane.showMessageDialog(null, "Fecha de inicio no válida, use formato dd/MM/yyyy");
			return;
		}
		else {
			i.setFechaInicioAlquiler(fechaInicio);
		}
		Date fechaFin = getFechaFromString(this.jtfFechaFin.getText());
		if (!jtfFechaFin.getText().trim().equals("") && 
				fechaFin == null) {
			JOptionPane.showMessageDialog(null, "Fecha de fin no válida, use formato dd/MM/yyyy");
			return;
		}
		else {
			i.setFechaFinAlquiler(fechaFin);
		}
		TipoMorosidad morosidadSeleccionada =
				(TipoMorosidad) this.jcbTipoMorosidad.getSelectedItem();
		i.setIdTipoMorosidad(morosidadSeleccionada.getId());
		Vivienda viviendaSeleccionada = 
				(Vivienda) this.jcbVivienda.getSelectedItem();
		i.setIdVivienda(viviendaSeleccionada.getId());
		i.setCuotaMensual(Float.parseFloat(this.jtfCuotaMensual.getText()));
		
		if (ControladorInquilino.guardaInquilino(i) > 0) {
			JOptionPane.showMessageDialog(null, "Inquilino almacenado");
		}
		else {
			JOptionPane.showMessageDialog(null, "Algo ha fallado");
		}
	}
	
	
	
	private Date getFechaFromString(String strDate) {
		try {
			return sdf.parse(strDate);
		} catch (Exception e) {
			return null;
		}
	}
}









