package net.h4ckx0r.vista.panels;

import net.h4ckx0r.controlador.ControladorTipologiaSexo;
import net.h4ckx0r.controlador.Utils;
import net.h4ckx0r.modelo.*;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import static net.h4ckx0r.controlador.Utils.stringToColor;

public class PanelPersona extends JPanel {

	private static final long serialVersionUID = 1L;

	private Persona personaActual;
	private Color colorFondoSistema = this.getBackground();

	private JTextField tfNombre;
	private JTextField tfApellido1;
	private JTextField tfApellido2;
	private JTextField tfDNI;
	private JTextField tfDireccion;
	private JTextField tfEmail;
	private JTextField tfTelefono;
	private JComboBox<TipologiaSexo> comboBoxSexo;
	private JLabel labelImage;
	private JPopupMenu popupMenuImage;
	private JMenuItem mntmDimensiones;
	private JTextField tfColorPreferido;

	List<TipologiaSexo> sexos = ControladorTipologiaSexo.getAllSexos();


	/**
	 * Create the panel.
	 */
	public PanelPersona() {
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{0, 0, 0, 0};
		gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
		gridBagLayout.columnWeights = new double[]{0.2, 1.0, 0.2, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
		setLayout(gridBagLayout);
		
		JLabel lblNewLabel = new JLabel("Nombre:");
		GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
		gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel.gridx = 0;
		gbc_lblNewLabel.gridy = 0;
		add(lblNewLabel, gbc_lblNewLabel);
		
		tfNombre = new JTextField();
		GridBagConstraints gbc_textField = new GridBagConstraints();
		gbc_textField.insets = new Insets(0, 0, 5, 5);
		gbc_textField.fill = GridBagConstraints.HORIZONTAL;
		gbc_textField.gridx = 1;
		gbc_textField.gridy = 0;
		add(tfNombre, gbc_textField);
		tfNombre.setColumns(10);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				mostrarPopup(e);
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				mostrarPopup(e);
			}

			private void mostrarPopup(MouseEvent e) {
				if (e.isPopupTrigger()) {
					popupMenuImage.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		});
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.gridheight = 6;
		gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.gridx = 2;
		gbc_scrollPane.gridy = 0;
		add(scrollPane, gbc_scrollPane);

		labelImage = new JLabel();
		labelImage.setHorizontalAlignment(SwingConstants.CENTER);
		scrollPane.setViewportView(labelImage);
		
		popupMenuImage = new JPopupMenu();
		scrollPane.add(popupMenuImage);
		
		mntmDimensiones = new JMenuItem("No hay imagen");
		mntmDimensiones.setEnabled(false);
		popupMenuImage.add(mntmDimensiones);
		popupMenuImage.addSeparator();
		JMenuItem mntmCambiarImagen = new JMenuItem("Cambiar Imagen");
		mntmCambiarImagen.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				solicitarImagenNativo();
			}
		});
		popupMenuImage.add(mntmCambiarImagen);

		JLabel lblNewLabel_1 = new JLabel("Primer Apellido:");
		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;
		add(lblNewLabel_1, gbc_lblNewLabel_1);
		
		tfApellido1 = new JTextField();
		GridBagConstraints gbc_textField_1 = new GridBagConstraints();
		gbc_textField_1.insets = new Insets(0, 0, 5, 5);
		gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
		gbc_textField_1.gridx = 1;
		gbc_textField_1.gridy = 1;
		add(tfApellido1, gbc_textField_1);
		tfApellido1.setColumns(10);
		
		JLabel lblNewLabel_2 = new JLabel("Segundo Apellido:");
		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 = 2;
		add(lblNewLabel_2, gbc_lblNewLabel_2);
		
		tfApellido2 = new JTextField();
		GridBagConstraints gbc_textField_2 = new GridBagConstraints();
		gbc_textField_2.insets = new Insets(0, 0, 5, 5);
		gbc_textField_2.fill = GridBagConstraints.HORIZONTAL;
		gbc_textField_2.gridx = 1;
		gbc_textField_2.gridy = 2;
		add(tfApellido2, gbc_textField_2);
		tfApellido2.setColumns(10);
		
		JLabel lblNewLabel_7 = new JLabel("Sexo:");
		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 = 3;
		add(lblNewLabel_7, gbc_lblNewLabel_7);
		
		comboBoxSexo = new JComboBox<>();
		GridBagConstraints gbc_comboBoxSexo = new GridBagConstraints();
		gbc_comboBoxSexo.insets = new Insets(0, 0, 5, 5);
		gbc_comboBoxSexo.fill = GridBagConstraints.HORIZONTAL;
		gbc_comboBoxSexo.gridx = 1;
		gbc_comboBoxSexo.gridy = 3;
		add(comboBoxSexo, gbc_comboBoxSexo);
		
		JLabel lblNewLabel_3 = new JLabel("DNI:");
		GridBagConstraints gbc_lblNewLabel_3 = new GridBagConstraints();
		gbc_lblNewLabel_3.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_3.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_3.gridx = 0;
		gbc_lblNewLabel_3.gridy = 4;
		add(lblNewLabel_3, gbc_lblNewLabel_3);
		
		tfDNI = new JTextField();
		GridBagConstraints gbc_textField_3 = new GridBagConstraints();
		gbc_textField_3.insets = new Insets(0, 0, 5, 5);
		gbc_textField_3.fill = GridBagConstraints.HORIZONTAL;
		gbc_textField_3.gridx = 1;
		gbc_textField_3.gridy = 4;
		add(tfDNI, gbc_textField_3);
		tfDNI.setColumns(10);
		
		JLabel lblNewLabel_4 = new JLabel("Dirección:");
		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;
		add(lblNewLabel_4, gbc_lblNewLabel_4);
		
		tfDireccion = new JTextField();
		GridBagConstraints gbc_textField_4 = new GridBagConstraints();
		gbc_textField_4.insets = new Insets(0, 0, 5, 5);
		gbc_textField_4.fill = GridBagConstraints.HORIZONTAL;
		gbc_textField_4.gridx = 1;
		gbc_textField_4.gridy = 5;
		add(tfDireccion, gbc_textField_4);
		tfDireccion.setColumns(10);
		
		JLabel lblNewLabel_5 = new JLabel("Email:");
		GridBagConstraints gbc_lblNewLabel_5 = new GridBagConstraints();
		gbc_lblNewLabel_5.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_5.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_5.gridx = 0;
		gbc_lblNewLabel_5.gridy = 6;
		add(lblNewLabel_5, gbc_lblNewLabel_5);
		
		tfEmail = new JTextField();
		GridBagConstraints gbc_textField_5 = new GridBagConstraints();
		gbc_textField_5.insets = new Insets(0, 0, 5, 5);
		gbc_textField_5.fill = GridBagConstraints.HORIZONTAL;
		gbc_textField_5.gridx = 1;
		gbc_textField_5.gridy = 6;
		add(tfEmail, gbc_textField_5);
		tfEmail.setColumns(10);
		
		JButton btnNewButton = new JButton("Cambiar Imagen");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				solicitarImagenNativo();
			}
		});
		GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
		gbc_btnNewButton.insets = new Insets(0, 0, 5, 0);
		gbc_btnNewButton.gridx = 2;
		gbc_btnNewButton.gridy = 6;
		add(btnNewButton, gbc_btnNewButton);
		
		JLabel lblNewLabel_6 = new JLabel("Teléfono");
		GridBagConstraints gbc_lblNewLabel_6 = new GridBagConstraints();
		gbc_lblNewLabel_6.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_6.anchor = GridBagConstraints.EAST;
		gbc_lblNewLabel_6.gridx = 0;
		gbc_lblNewLabel_6.gridy = 7;
		add(lblNewLabel_6, gbc_lblNewLabel_6);
		
		tfTelefono = new JTextField();
		GridBagConstraints gbc_textField_6 = new GridBagConstraints();
		gbc_textField_6.insets = new Insets(0, 0, 5, 5);
		gbc_textField_6.fill = GridBagConstraints.HORIZONTAL;
		gbc_textField_6.gridx = 1;
		gbc_textField_6.gridy = 7;
		add(tfTelefono, gbc_textField_6);
		tfTelefono.setColumns(10);
		
		JLabel lblNewLabel_8 = new JLabel("Color preferido:");
		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.gridx = 0;
		gbc_lblNewLabel_8.gridy = 8;
		add(lblNewLabel_8, gbc_lblNewLabel_8);
		
		tfColorPreferido = new JTextField();
		GridBagConstraints gbc_textFieldColor = new GridBagConstraints();
		gbc_textFieldColor.insets = new Insets(0, 0, 5, 5);
		gbc_textFieldColor.fill = GridBagConstraints.HORIZONTAL;
		gbc_textFieldColor.gridx = 1;
		gbc_textFieldColor.gridy = 8;
		add(tfColorPreferido, gbc_textFieldColor);
		tfColorPreferido.setColumns(10);
		
		JButton btnNewButton_1 = new JButton("Cambiar Color");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				solicitarColor();
			}
		});
		GridBagConstraints gbc_btnNewButton_1 = new GridBagConstraints();
		gbc_btnNewButton_1.insets = new Insets(0, 0, 5, 0);
		gbc_btnNewButton_1.gridx = 2;
		gbc_btnNewButton_1.gridy = 8;
		add(btnNewButton_1, gbc_btnNewButton_1);
		


	}

	private void setPersona(Persona persona) {
		tfNombre.setText(persona.getNombre());
		tfApellido1.setText(persona.getApellido1());
		tfApellido2.setText(persona.getApellido2());
		tfDNI.setText(persona.getDni());
		tfDireccion.setText(persona.getDireccion());
		tfEmail.setText(persona.getEmail());
		tfTelefono.setText(persona.getTelefono());
		if (persona.getColorPreferido() != null && !persona.getColorPreferido().isEmpty()) {
			this.setBackground(stringToColor(persona.getColorPreferido()));
		} else {
			this.setBackground(colorFondoSistema);
		}
		tfColorPreferido.setText(persona.getColorPreferido());
		personaActual = persona;
		actualizarSexo();
		ponerImagen();
	}

	private Persona getPersona() {
		personaActual.setNombre(tfNombre.getText());
		personaActual.setApellido1(tfApellido1.getText());
		personaActual.setApellido2(tfApellido2.getText());
		personaActual.setIdTipologiaSexo(((TipologiaSexo) comboBoxSexo.getSelectedItem()).getId());
		personaActual.setDni(tfDNI.getText());
		personaActual.setDireccion(tfDireccion.getText());
		personaActual.setEmail(tfEmail.getText());
		personaActual.setTelefono(tfTelefono.getText());
		personaActual.setColorPreferido(tfColorPreferido.getText());
		return personaActual;
	}

	public void setEstudianteActual(Estudiante estudiante) {
		setPersona(estudiante);
	}

	public Estudiante getEstudianteActual() {
		return (Estudiante) getPersona();
	}

	public void setProfesorActual(Profesor profesor) {
		setPersona(profesor);
	}

	public Profesor getProfesorActual() {
		return (Profesor) getPersona();
	}

	private void actualizarSexo() {
		comboBoxSexo.removeAllItems();
		for (TipologiaSexo sexo : sexos) {
			comboBoxSexo.addItem(sexo);
			if (personaActual.getIdTipologiaSexo() == sexo.getId()) {
				comboBoxSexo.setSelectedItem(sexo);
			}
		}
		if (personaActual.getIdTipologiaSexo() == -1) {
			comboBoxSexo.setSelectedIndex(-1);
		}
	}

	private void ponerImagen() {
		if (personaActual.getImagen() == null) {
			labelImage.setIcon(null);
			labelImage.setText("No hay imagen");
			mntmDimensiones.setText("No hay imagen");
		} else {
			ImageIcon icono = new ImageIcon(personaActual.getImagen());
			labelImage.setText("");
			labelImage.setIcon(icono);
			int[] dimensiones = getDimensionesImagen(icono);
			mntmDimensiones.setText("Dimensiones: " + dimensiones[0] + "x" + dimensiones[1]);
		}
	}

	private void solicitarImagen() {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileFilter(new FileNameExtensionFilter("Sólo imágenes: *.jpg, *.png", "jpg", "png"));
		int seleccion = fileChooser.showOpenDialog(this);
		if (seleccion == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			byte[] imagen = null;
			try {
				imagen = Files.readAllBytes(file.toPath());
			} catch (IOException e) {
				e.printStackTrace();
			}
			personaActual.setImagen(imagen);
			ponerImagen();
		}
	}




	private void solicitarImagenNativo() {
		JFrame frame = new JFrame();
		FileDialog fileChooser = new FileDialog(frame, "Seleccione una imagen", FileDialog.LOAD);
		fileChooser.setFilenameFilter(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
                return name.endsWith(".jpg") || name.endsWith(".png");
            }
		});
		fileChooser.setVisible(true);
		String folder = fileChooser.getDirectory();
		String file = fileChooser.getFile();
		if (file != null) {
			try {
				ImageIcon icono = new ImageIcon(folder + file);
				if (getDimensionesImagen(icono)[0] <= 300 && getDimensionesImagen(icono)[1] <= 300) {
					this.personaActual.setImagen(Files.readAllBytes(Paths.get(folder + file)));
					ponerImagen();
				} else {
					JOptionPane.showMessageDialog(this, "La imagen debe ser menor o igual de 300x300px");
				}
			} catch (IOException e) {
				throw new RuntimeException(e);
			}

		}
	}

	private int[] getDimensionesImagen(ImageIcon icon) {
		return new int[] {icon.getIconWidth(), icon.getIconHeight()};
	}


	private void solicitarColor() {
		Color color = JColorChooser.showDialog(this, "Seleccione un color", colorFondoSistema);
		if (color != null) {
			this.setBackground(color);
			tfColorPreferido.setText(Utils.colorToString(color));
		}
	}
}
