package interfaz;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.SystemColor;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import negocio.BloqueConstructivo;
import negocio.Idioma;
import negocio.Proyecto;
import negocio.Usuario;

import org.hibernate.Session;
import org.hibernate.Transaction;

import persistencia.UtilidadHibernate;
import java.awt.Color;
import javax.swing.BorderFactory;

public class MantenimientoUsuarios extends JDialog {

	private static final long serialVersionUID = 1L;

	private JPanel jContentPane = null;

	private JPanel jPanel = null;

	private JPanel jPanel1 = null;

	private JButton jButton = null;

	private JButton jButton1 = null;

	private JLabel jLabel = null;

	private JScrollPane jScrollPane = null;

	public JList jList = null;
	public DefaultListModel modelo = new DefaultListModel();
	


	public int actualizar = 0;
	
	public Principal padrePrincipal = null;
	
	public Proyecto proyecto_seleccionado;  //  @jve:decl-index=0:

	private JButton jButton2 = null;

	private JPanel jPanel2 = null;

	private JLabel jLabel2 = null;

	private JLabel jLabel3 = null;

	private JLabel jLabel4 = null;

	private JLabel jLabel5 = null;

	private JLabel jLabel6 = null;

	private JPanel jPanel3 = null;

	private JLabel jLabel7 = null;

	private JLabel jLabel8 = null;

	Integer numero_administradores, numero_desarrolladores, numero_usuarios, numero_total_usuarios;  //  @jve:decl-index=0:

	private JLabel jLabel9 = null;

	private JLabel jLabel10 = null;
	/**
	 * @param owner
	 */
	public MantenimientoUsuarios(Principal owner) {
		super(owner);
		padrePrincipal=owner;
		initialize();
	}
	
	public MantenimientoUsuarios(JDialog owner) {
		super(owner);
		initialize();
	}
	
	public void actualizaModelo()
	{
		try{
			Session session=null;
			
			session = UtilidadHibernate.getSessionFactory().openSession();
			
			Transaction tx = session.beginTransaction();
			
			
			modelo.removeAllElements();
			List messages = session.createQuery("from Usuario").list();
			for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
				Usuario usuario = (Usuario) iter.next();
				modelo.addElement(usuario);
			}
			jList.setModel(modelo);
			tx.commit();
			session.close();
			
			
		}	
		catch (Exception exp) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
		
	}
	
	public void EstadisticasNumeroUsuarios()
	{
		try{
			Session session=null;
			
			session = UtilidadHibernate.getSessionFactory().openSession();

			//Número de desarrolladores
			List messages = session.createQuery("from Usuario where rol='Developer'").list();
			numero_desarrolladores= messages.size();
			
			jLabel5.setText(numero_desarrolladores.toString());
		
			//Número de usuarios
			messages = session.createQuery("from Usuario where rol='Implanter'").list();
			numero_usuarios= messages.size();
			
			jLabel6.setText(numero_usuarios.toString());
		
			numero_total_usuarios=(numero_desarrolladores + numero_usuarios);
			jLabel10.setText(numero_total_usuarios.toString());
			
			session.close();
			
		}	
		catch (Exception exp) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
		
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		padrePrincipal.Tamaño_ventana(this);
		this.setPreferredSize(new Dimension(420, 400));
		this.setModal(true);
		int idelemento = padrePrincipal.jList.getSelectedIndex();
		if (padrePrincipal.idioma.equals("español"))
			this.setTitle("Mantenimiento de usuarios");
		else
			this.setTitle("Management of users");
		this.setContentPane(getJContentPane());
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowOpened(java.awt.event.WindowEvent e) {
				actualizaModelo();
				EstadisticasNumeroUsuarios();
			}
		});
		
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getJPanel(), BorderLayout.EAST);
			jContentPane.add(getJPanel1(), BorderLayout.CENTER);
		}
		return jContentPane;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			jPanel = new JPanel();
			jPanel.setLayout(new FlowLayout());
			jPanel.setPreferredSize(new Dimension(115, 26));
			jPanel.setBackground(SystemColor.controlHighlight);
			jPanel.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.lightGray));
			jPanel.add(getJButton(), null);
			jPanel.add(getJButton2(), null);
			jPanel.add(getJButton1(), null);
		}
		return jPanel;
	}

	/**
	 * This method initializes jPanel1	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel1() {
		if (jPanel1 == null) {
			GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
			gridBagConstraints3.gridx = 0;
			gridBagConstraints3.fill = GridBagConstraints.BOTH;
			gridBagConstraints3.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints3.gridy = 2;
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.fill = GridBagConstraints.BOTH;
			gridBagConstraints.gridy = 1;
			gridBagConstraints.weightx = 1.0;
			gridBagConstraints.weighty = 1.0;
			gridBagConstraints.insets = new Insets(5, 5, 0, 5);
			gridBagConstraints.gridx = 0;
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.gridx = 0;
			gridBagConstraints1.insets = new Insets(10, 0, 0, 0);
			gridBagConstraints1.gridy = 0;
			jLabel = new JLabel();
			if (padrePrincipal.idioma.equals("español"))
				jLabel.setText("Lista de usuarios");
			else
				jLabel.setText("List of users");
			jPanel1 = new JPanel();
			jPanel1.setLayout(new GridBagLayout());
			jPanel1.setBackground(new Color(238, 238, 238));
			jPanel1.add(jLabel, gridBagConstraints1);
			jPanel1.add(getJScrollPane(), gridBagConstraints);
			jPanel1.add(getJPanel2(), gridBagConstraints3);
		}
		return jPanel1;
	}

	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton() {
		if (jButton == null) {
			jButton = new JButton();
			if (padrePrincipal.idioma.equals("español"))
				jButton.setText("Añadir");
			else
				jButton.setText("Add");
			jButton.setPreferredSize(new Dimension(105, 26));
			jButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					NuevoUsuario ventana = new NuevoUsuario(MantenimientoUsuarios.this, false);
					ventana.setLocationRelativeTo(MantenimientoUsuarios.this);
					ventana.setVisible(true);
					actualizar=0;
				}
			});
		}
		return jButton;
	}

	/**
	 * This method initializes jButton1	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			if (padrePrincipal.idioma.equals("español"))
				jButton1.setText("Borrar");
			else
				jButton1.setText("Delete");
			jButton1.setPreferredSize(new Dimension(105, 26));
			jButton1.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					
					try{			

						int idvista = jList.getSelectedIndex();
						if (idvista!=-1){
							
//							
							
							Usuario usuario = (Usuario) modelo.getElementAt(idvista);
							
							int n;
							if (padrePrincipal.idioma.equals("español")){
								n = JOptionPane.showConfirmDialog(
									MantenimientoUsuarios.this, "¿Estás seguro de que quieres borrar el usuario '" + usuario.getLogin() + "'?",
									"Advertencia",
									JOptionPane.YES_NO_OPTION);
							}
							else {
								n = JOptionPane.showConfirmDialog(
										MantenimientoUsuarios.this, "Are you sure you want to delete el usuario '" + usuario.getLogin() + "'?",
										"Warning",
										JOptionPane.YES_NO_OPTION);
								
							}
								
							if (n == JOptionPane.YES_OPTION) {
								//Creamos la sesión para almacenar el nombre del proyecto en la BD
								Session session=null;
								
								session = UtilidadHibernate.getSessionFactory().openSession();
								
								List messages = session.createQuery("from Usuario where rol = 'Developer' ").list();
								
								session.close();
								
								if (usuario.getRol().equals("Implanter") || messages.size()>1){
								
									session = UtilidadHibernate.getSessionFactory().openSession();
									
									Transaction tx = session.beginTransaction();
									
									//Borramos el objeto
									session.delete(usuario);
									
									//Borramos el objeto de la lista
									modelo.removeElement(usuario);
																																										
									tx.commit();
									actualizaModelo();
									EstadisticasNumeroUsuarios();
									session.close();
								}
								else{
									if (padrePrincipal.idioma.equals("español"))
										throw new Exception("Error, Sólo existe un único desarrollador. No se puede borrar.");
									else
										throw new Exception("Error, There is only one developer. You can't delete it.");
								}
								
							}
								
						}
						else{
							if (padrePrincipal.idioma.equals("español"))
								throw new Exception("Error, selecciona un usuario de la lista");
							else
								throw new Exception("Error, select an user of the list.");
						}
					}	
					catch (Exception exp) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}
					
					//actualizaModelo();
				}
			});
		}
		return jButton1;
	}

	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getJList());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jList	
	 * 	
	 * @return javax.swing.JList	
	 */
	private JList getJList() {
		if (jList == null) {
			jList = new JList();
		}
		return jList;
	}

	/**
	 * This method initializes jButton2	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton2() {
		if (jButton2 == null) {
			jButton2 = new JButton();
			if (padrePrincipal.idioma.equals("español"))
				jButton2.setText("Modificar");
			else
				jButton2.setText("Modify");
			jButton2.setPreferredSize(new Dimension(106, 26));
			jButton2.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					try{
						int idfase = jList.getSelectedIndex();
						if (idfase==-1){
							if (padrePrincipal.idioma.equals("español"))
								throw new Exception("Error, selecciona un usuario de la lista");
							else
								throw new Exception("Error, select a user of the list");
						}
						else{
							NuevoUsuario ventana = new NuevoUsuario(MantenimientoUsuarios.this, true);
							ventana.setLocationRelativeTo(MantenimientoUsuarios.this);
							ventana.setVisible(true);
						}
					}	
					catch (Exception exp) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			});
		}
		return jButton2;
	}

	/**
	 * This method initializes jPanel2	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel2() {
		if (jPanel2 == null) {
			GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
			gridBagConstraints11.gridx = 0;
			gridBagConstraints11.gridy = 2;
			jLabel8 = new JLabel();
			GridBagConstraints gridBagConstraints10 = new GridBagConstraints();
			gridBagConstraints10.gridx = 0;
			gridBagConstraints10.anchor = GridBagConstraints.WEST;
			gridBagConstraints10.insets = new Insets(5, 0, 0, 0);
			gridBagConstraints10.gridy = 0;
			jLabel7 = new JLabel();
			if (padrePrincipal.idioma.equals("español"))
				jLabel7.setText("Estadísticas:");
			else
				jLabel7.setText("Statistics:");
			GridBagConstraints gridBagConstraints9 = new GridBagConstraints();
			gridBagConstraints9.gridx = 0;
			gridBagConstraints9.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints9.gridy = 1;
			jLabel6 = new JLabel();
			//jLabel6.setText("JLabel");
			jLabel5 = new JLabel();
			//jLabel5.setText("JLabel");
			jLabel4 = new JLabel();
			//jLabel4.setText("JLabel");
			jLabel3 = new JLabel();
			if (padrePrincipal.idioma.equals("español"))
				jLabel3.setText("Implantadores");
			else
				jLabel3.setText("Implanters");
			jLabel2 = new JLabel();
			if (padrePrincipal.idioma.equals("español"))
				jLabel2.setText("Desarrolladores");
			else
				jLabel2.setText("Developers");

			jPanel2 = new JPanel();
			jPanel2.setLayout(new GridBagLayout());
			jPanel2.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.lightGray));
			jPanel2.add(getJPanel3(), gridBagConstraints9);
			jPanel2.setBackground(new Color(238, 238, 238));
			jPanel2.add(jLabel7, gridBagConstraints10);
			jPanel2.add(jLabel8, gridBagConstraints11);
		}
		return jPanel2;
	}

	/**
	 * This method initializes jPanel3	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel3() {
		if (jPanel3 == null) {
			GridBagConstraints gridBagConstraints13 = new GridBagConstraints();
			gridBagConstraints13.gridx = 3;
			gridBagConstraints13.insets = new Insets(0, 5, 5, 0);
			gridBagConstraints13.gridy = 7;
			jLabel10 = new JLabel();
			//jLabel10.setText("JLabel");
			jLabel10.setForeground(Color.BLUE);
			GridBagConstraints gridBagConstraints12 = new GridBagConstraints();
			gridBagConstraints12.gridx = 2;
			gridBagConstraints12.anchor = GridBagConstraints.WEST;
			gridBagConstraints12.insets = new Insets(0, 0, 5, 0);
			gridBagConstraints12.gridy = 7;
			jLabel9 = new JLabel();
			jLabel9.setForeground(Color.BLUE);
			jLabel9.setText("Total");
			GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
			gridBagConstraints2.anchor = GridBagConstraints.WEST;
			gridBagConstraints2.gridy = 5;
			gridBagConstraints2.gridx = 2;
			GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
			gridBagConstraints4.anchor = GridBagConstraints.WEST;
			gridBagConstraints4.gridx = 2;
			gridBagConstraints4.gridy = 6;
			gridBagConstraints4.insets = new Insets(0, 0, 0, 0);
			GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
			gridBagConstraints6.insets = new Insets(0, 5, 0, 0);
			gridBagConstraints6.gridy = 2;
			gridBagConstraints6.gridx = 3;
			GridBagConstraints gridBagConstraints7 = new GridBagConstraints();
			gridBagConstraints7.insets = new Insets(0, 5, 0, 0);
			gridBagConstraints7.gridy = 5;
			gridBagConstraints7.gridx = 3;
			GridBagConstraints gridBagConstraints8 = new GridBagConstraints();
			gridBagConstraints8.insets = new Insets(0, 5, 0, 0);
			gridBagConstraints8.gridy = 6;
			gridBagConstraints8.gridx = 3;
			jPanel3 = new JPanel();
			jPanel3.setLayout(new GridBagLayout());
			jPanel3.add(jLabel6, gridBagConstraints8);
			jPanel3.setBackground(new Color(238, 238, 238));
			jPanel3.add(jLabel5, gridBagConstraints7);
			jPanel3.add(jLabel4, gridBagConstraints6);
			jPanel3.add(jLabel3, gridBagConstraints4);
			jPanel3.add(jLabel2, gridBagConstraints2);
			jPanel3.add(jLabel9, gridBagConstraints12);
			jPanel3.add(jLabel10, gridBagConstraints13);
		}
		return jPanel3;
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"
