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.awt.Toolkit;
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.Plantilla;


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

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

public class MantenimientoBloque 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();

	private JButton jButton2 = null;
	
	public int actualizar = 0;
	
	public Principal padrePrincipal = null;

	private JButton jButton3 = null;

	private JButton jButton4 = null;

	private JButton jButton31 = null;

	private JPanel jPanel2 = null;

	private JPanel jPanel3 = null;

	private JLabel jLabel9 = null;

	private JLabel jLabel10 = null;

	private JLabel jLabel7 = null;

	private JLabel jLabel8 = null;
	
	private Integer numero_bloques;


	/**
	 * @param owner
	 */
	public MantenimientoBloque(Principal owner) {
		super(owner);
		padrePrincipal=owner;
		initialize();
	}
	
	public MantenimientoBloque(JDialog owner) {
		super(owner);
		initialize();
	}
	
	public void actualizaModelo()
	{
		try{
			Session session=null;
			
			session = UtilidadHibernate.getSessionFactory().openSession();
			
			Transaction tx = session.beginTransaction();
			
			int idelemento = padrePrincipal.jList.getSelectedIndex();
			Plantilla plantilla = (Plantilla) padrePrincipal.modelo.getElementAt(idelemento);

			modelo.removeAllElements();
			List messages = session.createQuery("from BloqueConstructivo m where id_plantilla = '"+plantilla.getIdPlantilla()+"' order by nombre asc").list();
			//System.out.println("Número de elementos: " + messages.size());
			for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
				BloqueConstructivo bloque = (BloqueConstructivo) iter.next();
				modelo.addElement(bloque);
			}
			jList.setModel(modelo);
			tx.commit();
			session.close();
			
			
		}	
		catch (Exception exp) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
		
	}
	
	public void EstadisticasNumeroBloques()
	{
		try{
			Session session=null;
			
			session = UtilidadHibernate.getSessionFactory().openSession();

			int idelemento = padrePrincipal.jList.getSelectedIndex();
			Plantilla plantilla = (Plantilla) padrePrincipal.modelo.getElementAt(idelemento);
			
			//Número de administradores
			List messages = session.createQuery("from BloqueConstructivo where id_plantilla = '"+plantilla.getIdPlantilla()+"'").list();
			numero_bloques= messages.size();
			
			jLabel10.setText(numero_bloques.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(400, 270));
		this.setModal(true);
		int idelemento = padrePrincipal.jList.getSelectedIndex();
		Plantilla plantilla = (Plantilla) padrePrincipal.modelo.getElementAt(idelemento);
		if (padrePrincipal.idioma.equals("español"))
			this.setTitle("Mantenimiento de bloques (" + plantilla.getNombre() + ")");
		else
			this.setTitle("Management of blocks (" + plantilla.getNombre() + ")");
		this.setContentPane(getJContentPane());
		this.addWindowListener(new java.awt.event.WindowAdapter() {   
			public void windowClosing(java.awt.event.WindowEvent e) {    
				padrePrincipal.ActualizaListaBloques();
			}
			public void windowOpened(java.awt.event.WindowEvent e) {
				actualizaModelo();
				EstadisticasNumeroBloques();
			}
		});
		
	}

	/**
	 * 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(getJButton31(), null);
			jPanel.add(getJButton1(), null);
			jPanel.add(getJButton2(), null);
			//jPanel.add(getJButton3(), null);
			jPanel.add(getJButton4(), null);
		}
		return jPanel;
	}

	/**
	 * This method initializes jPanel1	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel1() {
		if (jPanel1 == null) {
			GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
			gridBagConstraints4.gridx = 0;
			gridBagConstraints4.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints4.fill = GridBagConstraints.HORIZONTAL;
			gridBagConstraints4.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 bloques");
			else
				jLabel.setText("Blocklist");
			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(), gridBagConstraints4);
		}
		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) {
					MantenimientoVista v = new MantenimientoVista(padrePrincipal);
					MantenimientoFase f = new MantenimientoFase(padrePrincipal);
					NuevoBloque ventana = new NuevoBloque(MantenimientoBloque.this,v,f, false);
					ventana.setLocationRelativeTo(MantenimientoBloque.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 idbloque = jList.getSelectedIndex();
						if (idbloque!=-1){
					
							
							
							BloqueConstructivo bloque = (BloqueConstructivo) modelo.getElementAt(idbloque);
							
							int n;
							if (padrePrincipal.idioma.equals("español")){
								n = JOptionPane.showConfirmDialog(
									MantenimientoBloque.this, "¿Estás seguro de que quieres borrar el bloque '" + bloque.getNombre() + "'?",
									"Advertencia",
									JOptionPane.YES_NO_OPTION);
							}
							else {
								n = JOptionPane.showConfirmDialog(
										MantenimientoBloque.this, "Are you sure you want to delete the block '" + bloque.getNombre() + "'?",
										"Warning",
										JOptionPane.YES_NO_OPTION);
								
							}
								
							if (n == JOptionPane.YES_OPTION) {
								//Creamos la sesión para almacenar el nombre del plantilla en la BD
								
								
								Session session=null;
								
								session = UtilidadHibernate.getSessionFactory().openSession();
													
								//Borramos el objeto de la lista
								
																																									
								Transaction tx = session.beginTransaction();
								session.delete(bloque);
								tx.commit();
								
								modelo.removeElement(bloque);
								
								//Actualizamos la interfaz (lista de bloques)
								actualizaModelo();
								EstadisticasNumeroBloques();
								session.close();
							}
						}
						else{
							if (padrePrincipal.idioma.equals("español"))
								throw new Exception("Error, selecciona un bloque de la lista");
							else
								throw new Exception("Error, select a block 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("Abrir Editor");
			else
				jButton2.setText("Open Editor");
			jButton2.setPreferredSize(new Dimension(105, 26));
			jButton2.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					try{
						int indice = jList.getSelectedIndex();
						if (indice!=-1){
							EditorDeBloques ventana = new EditorDeBloques(MantenimientoBloque.this, padrePrincipal);
							/*Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
							ventana.setSize(screenSize);*/
							ventana.setLocationRelativeTo(MantenimientoBloque.this);
							ventana.setVisible(true);
							actualizar=1;
							
						}
						else{
							if (padrePrincipal.idioma.equals("español"))
								throw new Exception("Error, selecciona un bloque de la lista");
							else
								throw new Exception("Error, select a block of the list");
						}
					}
					catch (Exception exp) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			});
		}
		return jButton2;
	}

	/**
	 * This method initializes jButton4	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton4() {
		if (jButton4 == null) {
			jButton4 = new JButton();
			if (padrePrincipal.idioma.equals("español"))
				jButton4.setText("Instancias");
			else
				jButton4.setText("Instances");
			jButton4.setPreferredSize(new Dimension(105, 26));
			jButton4.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					try{
						int indice = jList.getSelectedIndex();
						if (indice!=-1){
							MantenimientoInstancia ventana = new MantenimientoInstancia(MantenimientoBloque.this);
							ventana.setLocationRelativeTo(MantenimientoBloque.this);
							ventana.setVisible(true);
						}
						else{
							if (padrePrincipal.idioma.equals("español"))
								throw new Exception("Error, selecciona un bloque de la lista");
							else
								throw new Exception("Error, select a block of the list");
						}
					}
					catch (Exception exp) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}
					
					
				}
			});
			if ((padrePrincipal.usuario!=null && (padrePrincipal.usuario.getRol().equals("Administrador") || padrePrincipal.usuario.getRol().equals("Usuario"))))
				jButton4.setVisible(true);
			else
				jButton4.setVisible(false);
		}
		return jButton4;
	}

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

						int idbloque = jList.getSelectedIndex();
						if (idbloque!=-1){
							MantenimientoVista v = new MantenimientoVista(padrePrincipal);
							MantenimientoFase f = new MantenimientoFase(padrePrincipal);
							NuevoBloque ventana = new NuevoBloque(MantenimientoBloque.this,v,f, true);
							ventana.setLocationRelativeTo(MantenimientoBloque.this);
							ventana.setVisible(true);
					
						}
						else{
							if (padrePrincipal.idioma.equals("español"))
								throw new Exception("Error, selecciona un bloque de la lista");
							else
								throw new Exception("Error, select a block of the list");
						}
					}	
					catch (Exception exp) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			});
		}
		return jButton31;
	}

	/**
	 * 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.anchor = GridBagConstraints.WEST;
			gridBagConstraints10.gridx = 0;
			gridBagConstraints10.gridy = 0;
			gridBagConstraints10.insets = new Insets(5, 0, 0, 0);
			jLabel7 = new JLabel();
			if(padrePrincipal.idioma.equals("español"))
				jLabel7.setText("Estadísticas:");
			else
				jLabel7.setText("Statistics:");
			GridBagConstraints gridBagConstraints9 = new GridBagConstraints();
			gridBagConstraints9.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints9.gridy = 1;
			gridBagConstraints9.gridx = 0;
			jPanel2 = new JPanel();
			jPanel2.setLayout(new GridBagLayout());
			jPanel2.setBackground(new Color(238, 238, 238));
			jPanel2.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.lightGray));
			jPanel2.add(getJPanel3(), gridBagConstraints9);
			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.insets = new Insets(0, 5, 5, 0);
			gridBagConstraints13.gridy = 7;
			gridBagConstraints13.gridx = 3;
			jLabel10 = new JLabel();
			jLabel10.setForeground(Color.BLUE);
			//jLabel10.setText("JLabel");
			GridBagConstraints gridBagConstraints12 = new GridBagConstraints();
			gridBagConstraints12.anchor = GridBagConstraints.WEST;
			gridBagConstraints12.gridx = 2;
			gridBagConstraints12.gridy = 7;
			gridBagConstraints12.insets = new Insets(0, 0, 5, 0);
			jLabel9 = new JLabel();
			jLabel9.setForeground(Color.BLUE);
			jLabel9.setText("Total");
			jPanel3 = new JPanel();
			jPanel3.setBackground(new Color(238, 238, 238));
			jPanel3.setLayout(new GridBagLayout());
			jPanel3.add(jLabel9, gridBagConstraints12);
			jPanel3.add(jLabel10, gridBagConstraints13);
		}
		return jPanel3;
	}

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