package interfaz;

import javax.swing.JPanel;
import java.awt.Frame;
import java.awt.BorderLayout;
import javax.swing.JDialog;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import java.awt.GridBagConstraints;

import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;

import negocio.BloqueConstructivo;
import negocio.ComponenteBloque;

import negocio.Proyecto;


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

import persistencia.UtilidadHibernate;

import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.SystemColor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JScrollPane;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import java.awt.event.KeyEvent;

public class MantenimientoComponente extends JDialog {

	private static final long serialVersionUID = 1L;

	private JPanel jContentPane = null;

	private JPanel jPanel1 = null;

	private JLabel jLabel = null;

	public JList jList = null;
	public DefaultListModel modelo = new DefaultListModel();
	
	public int prueba;
	
	public EditorDeBloques padreEditorDeBloques;

	private JScrollPane jScrollPane = null;

	private JPanel jPanel2 = null;

	private JButton jButton3 = null;

	private JButton jButton4 = null;

	private JLabel jLabel1 = null;
	
	ComponenteBloque elemento_primero, elemento_ultimo;

	private JPanel jPanel21 = null;

	private JPanel jPanel3 = null;

	private JLabel jLabel9 = null;

	private JLabel jLabel10 = null;

	private JLabel jLabel7 = null;

	private JLabel jLabel8 = null;
	
	private Integer numero_componentes;  //  @jve:decl-index=0:

	/**
	 * @param owner
	 */
	public MantenimientoComponente(EditorDeBloques owner) {
		super(owner);
		padreEditorDeBloques=owner;
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		if (padreEditorDeBloques.desdePrincipal)
			padreEditorDeBloques.padrePrincipal.Tamaño_ventana(this);
		else
			padreEditorDeBloques.padreMantenimientoBloque.padrePrincipal.Tamaño_ventana(this);
		this.setModal(true);
		if (padreEditorDeBloques.idioma.equals("español"))
			this.setTitle("Ordenar componentes");
		else
			this.setTitle("Order components");
		this.setContentPane(getJContentPane());
		this.addWindowListener(new java.awt.event.WindowAdapter() {   
			public void windowClosing(java.awt.event.WindowEvent e) {    
				padreEditorDeBloques.PintarComponentes();
				padreEditorDeBloques.jPanel1.updateUI();
			}
			public void windowOpened(java.awt.event.WindowEvent e) {
				actualizaModelo();
				jButton4.setEnabled(false);
				jButton3.setEnabled(false);
				EstadisticasNumeroComponentes();
			}
		});
	}
	
	private BloqueConstructivo ObtenerBloque (){
		int idbloque;
		BloqueConstructivo bloque;
		if(padreEditorDeBloques.desdePrincipal){
			idbloque = padreEditorDeBloques.padrePrincipal.jList3.getSelectedIndex();
			bloque = (BloqueConstructivo) padreEditorDeBloques.padrePrincipal.modeloBloque.getElementAt(idbloque);
		}
		else{
			idbloque = padreEditorDeBloques.padreMantenimientoBloque.jList.getSelectedIndex();
			bloque = (BloqueConstructivo) padreEditorDeBloques.padreMantenimientoBloque.modelo.getElementAt(idbloque);
		}
		
		return bloque;
	}

	public void actualizaModelo()
	{
		try{
			Session session=null;
			
			session = UtilidadHibernate.getSessionFactory().openSession();
			
			Transaction tx = session.beginTransaction();

			modelo.removeAllElements();
			
			BloqueConstructivo bloque = ObtenerBloque();
			
			List messages = session.createQuery("from ComponenteBloque where id_bloque ='"+bloque.getIdBloque()+"' order by posicion").list();
			
			//System.out.println("Número de elementos: " + messages.size());
			for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
				ComponenteBloque componente = (ComponenteBloque) iter.next();
				modelo.addElement(componente);
			}
			jList.setModel(modelo);
			tx.commit();
			session.close();
		}	
		catch (Exception exp) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
		
	}

	public void EstadisticasNumeroComponentes()
	{
		try{
			Session session=null;
			
			session = UtilidadHibernate.getSessionFactory().openSession();

			
			BloqueConstructivo bloque = ObtenerBloque();
			
			List messages = session.createQuery("from ComponenteBloque where id_bloque = '"+bloque.getIdBloque()+"'").list();
			numero_componentes= messages.size();
			
			jLabel10.setText(numero_componentes.toString());
			
			session.close();
			
		}	
		catch (Exception exp) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
		
	}

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

	/**
	 * This method initializes jPanel1	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel1() {
		if (jPanel1 == null) {
			GridBagConstraints gridBagConstraints31 = new GridBagConstraints();
			gridBagConstraints31.gridx = 0;
			gridBagConstraints31.fill = GridBagConstraints.HORIZONTAL;
			gridBagConstraints31.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints31.gridy = 2;
			GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
			gridBagConstraints21.gridx = 1;
			gridBagConstraints21.insets = new Insets(10, 0, 0, 5);
			gridBagConstraints21.gridy = 0;
			jLabel1 = new JLabel();
			if (padreEditorDeBloques.idioma.equals("español"))
				jLabel1.setText("Orden");
			else
				jLabel1.setText("Order");
			GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
			gridBagConstraints11.gridx = 1;
			gridBagConstraints11.fill = GridBagConstraints.HORIZONTAL;
			gridBagConstraints11.insets = new Insets(5, 0, 5, 5);
			gridBagConstraints11.ipadx = 0;
			gridBagConstraints11.ipady = 0;
			gridBagConstraints11.weighty = 0.0;
			gridBagConstraints11.anchor = GridBagConstraints.EAST;
			gridBagConstraints11.weightx = 0.0;
			gridBagConstraints11.gridy = 1;
			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 (padreEditorDeBloques.idioma.equals("español"))
				jLabel.setText("Lista de componentes");
			else
				jLabel.setText("List of components");
			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(), gridBagConstraints11);
			jPanel1.add(jLabel1, gridBagConstraints21);
			jPanel1.add(getJPanel21(), gridBagConstraints31);
		}
		return jPanel1;
	}

	/**
	 * This method initializes jList	
	 * 	
	 * @return javax.swing.JList	
	 */
	private JList getJList() {
		if (jList == null) {
			jList = new JList();
			jList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
				public void valueChanged(javax.swing.event.ListSelectionEvent e) {
					try {
						
						
						int elemento = jList.getSelectedIndex();
						
						if (elemento >-1){
						
							elemento_primero = (ComponenteBloque) modelo.getElementAt(0);
							
							int posicion_ultima = modelo.size()-1;
							
							elemento_ultimo = (ComponenteBloque) modelo.getElementAt(posicion_ultima);
							
							ComponenteBloque componente = (ComponenteBloque) modelo.getElementAt(elemento);
							
							if (modelo.size()==1){
								jButton3.setEnabled(false);
								jButton4.setEnabled(false);
							}
							else if (componente.getIdComponenteBloque()==elemento_primero.getIdComponenteBloque()){
								jButton3.setEnabled(false);
								jButton4.setEnabled(true);
							}
							else if (componente.getIdComponenteBloque()==elemento_ultimo.getIdComponenteBloque()){
								jButton4.setEnabled(false);
								jButton3.setEnabled(true);
							}
							else{
								jButton3.setEnabled(true);
								jButton4.setEnabled(true);
							}
						}

					}
					catch (Exception exp) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			});
		}
		return jList;
	}

	/**
	 * 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 jPanel2	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel2() {
		if (jPanel2 == null) {
			GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
			gridBagConstraints3.insets = new Insets(0, 0, 0, 0);
			gridBagConstraints3.weighty = 1.0;
			gridBagConstraints3.fill = GridBagConstraints.NONE;
			gridBagConstraints3.weightx = 1.0;
			GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
			gridBagConstraints2.gridx = 0;
			gridBagConstraints2.insets = new Insets(0, 0, 0, 0);
			gridBagConstraints2.weightx = 1.0;
			gridBagConstraints2.weighty = 1.0;
			gridBagConstraints2.fill = GridBagConstraints.NONE;
			gridBagConstraints2.gridy = 1;
			jPanel2 = new JPanel();
			jPanel2.setLayout(new GridBagLayout());
			jPanel2.setPreferredSize(new Dimension(30, 60));
			jPanel2.setMinimumSize(new Dimension(0, 0));
			jPanel2.setBackground(new Color(238, 238, 238));
			jPanel2.add(getJButton3(), gridBagConstraints3);
			jPanel2.add(getJButton4(), gridBagConstraints2);
		}
		return jPanel2;
	}

	/**
	 * This method initializes jButton3	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton3() {
		if (jButton3 == null) {
			jButton3 = new JButton();
			jButton3.setPreferredSize(new Dimension(22, 22));
			jButton3.setHorizontalTextPosition(SwingConstants.CENTER);
			jButton3.setMnemonic(KeyEvent.VK_UNDEFINED);
			jButton3.setIcon(new ImageIcon("./src/imagenes/flechaArriba.PNG"));
			jButton3.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					
					try{
						int elemento = jList.getSelectedIndex();
						
						if (elemento != -1){
							ComponenteBloque componente = (ComponenteBloque) modelo.getElementAt(elemento);
							int nueva_posicion = componente.getPosicion() - 1;
							
							//HACEMOS EL INTERCAMBIO DE ORDEN
							//Ponemos el nuevo orden al elemento que está encima del elemento seleccionado
							for (int i=0; i< modelo.size(); i++){
								ComponenteBloque componente2 = (ComponenteBloque) modelo.getElementAt(i);
								
								if (componente2.getPosicion()==nueva_posicion){
									componente2.setPosicion(nueva_posicion+1);
									
									Session session = UtilidadHibernate.getSessionFactory().openSession();
									Transaction tx = session.beginTransaction();
									session.update(componente2);
									
									tx.commit();
									session.close();
								}
								
							}
							
							//Ponemos el nuevo orden al elemento seleccionado
							componente.setPosicion(nueva_posicion);
							Session session = UtilidadHibernate.getSessionFactory().openSession();
							Transaction tx = session.beginTransaction();
							session.update(componente);
							
							tx.commit();
							session.close();
							
							jList.updateUI();
							
							actualizaModelo();
							jList.updateUI();
							jList.setSelectedIndex(elemento-1);
							
							elemento_primero = (ComponenteBloque) modelo.getElementAt(0);
							
							int posicion_ultima = modelo.size()-1;
							
							elemento_ultimo = (ComponenteBloque) modelo.getElementAt(posicion_ultima);
							
							
							ComponenteBloque componente2 = (ComponenteBloque) modelo.getElementAt(elemento-1);
							
							if (modelo.size()==1){
								jButton3.setEnabled(false);
								jButton4.setEnabled(false);
							}
							else if (componente.getIdComponenteBloque()==elemento_primero.getIdComponenteBloque()){
								jButton3.setEnabled(false);
								jButton4.setEnabled(true);
							}
							else if (componente.getIdComponenteBloque()==elemento_ultimo.getIdComponenteBloque()){
								jButton4.setEnabled(false);
								jButton3.setEnabled(true);
							}
							else{
								jButton3.setEnabled(true);
								jButton4.setEnabled(true);
							}
						}
						else{
							if (padreEditorDeBloques.idioma.equals("español"))
								throw new Exception("Error, selecciona una componente de la lista");
							else
								throw new Exception("Error, select a of th phase of the list");
						}
					}
					catch (Exception exp) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			});
		}
		return jButton3;
	}

	/**
	 * This method initializes jButton4	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton4() {
		if (jButton4 == null) {
			jButton4 = new JButton();
			jButton4.setPreferredSize(new Dimension(22, 22));
			jButton4.setIcon(new ImageIcon("./src/imagenes/flechaAbajo.PNG"));
			jButton4.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					try{
						int elemento = jList.getSelectedIndex();
						
						if (elemento != -1){
							ComponenteBloque componente = (ComponenteBloque) modelo.getElementAt(elemento);
							int nueva_posicion = componente.getPosicion() + 1;
							
							//HACEMOS EL INTERCAMBIO DE ORDEN
							//Ponemos el nuevo orden al elemento que está encima (en la lista) del elemento seleccionado
							for (int i=0; i< modelo.size(); i++){
								ComponenteBloque componente2 = (ComponenteBloque) modelo.getElementAt(i);
								if (componente2.getPosicion()==nueva_posicion){
									componente2.setPosicion(nueva_posicion-1);
									Session session = UtilidadHibernate.getSessionFactory().openSession();
									Transaction tx = session.beginTransaction();
									session.update(componente2);
									
									tx.commit();
									session.close();
								}
							}
							
							//Ponemos el nuevo orden al elemento seleccionado
							componente.setPosicion(nueva_posicion);
							Session session = UtilidadHibernate.getSessionFactory().openSession();
							Transaction tx = session.beginTransaction();
							session.update(componente);
							
							tx.commit();
							session.close();
							
							jList.updateUI();
							
							actualizaModelo();
							jList.updateUI();
							jList.setSelectedIndex(elemento+1);
							
							elemento_primero = (ComponenteBloque) modelo.getElementAt(0);
							
							int posicion_ultima = modelo.size()-1;
							
							elemento_ultimo = (ComponenteBloque) modelo.getElementAt(posicion_ultima);
							
							
							ComponenteBloque componente2 = (ComponenteBloque) modelo.getElementAt(elemento+1);
							
							if (modelo.size()==1){
								jButton3.setEnabled(false);
								jButton4.setEnabled(false);
							}
							else if (componente.getIdComponenteBloque()==elemento_primero.getIdComponenteBloque()){
								jButton3.setEnabled(false);
								jButton4.setEnabled(true);
							}
							else if (componente.getIdComponenteBloque()==elemento_ultimo.getIdComponenteBloque()){
								jButton4.setEnabled(false);
								jButton3.setEnabled(true);
							}
							else{
								jButton3.setEnabled(true);
								jButton4.setEnabled(true);
							}
						}
						else{
							if (padreEditorDeBloques.idioma.equals("español"))
								throw new Exception("Error, selecciona una componente de la lista");
							else
								throw new Exception("Error, select a of th phase of the list");
						}
					}
					catch (Exception exp) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			});
		}
		return jButton4;
	}

	/**
	 * This method initializes jPanel21	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel21() {
		if (jPanel21 == null) {
			GridBagConstraints gridBagConstraints111 = new GridBagConstraints();
			gridBagConstraints111.gridx = 0;
			gridBagConstraints111.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 (padreEditorDeBloques.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;
			jPanel21 = new JPanel();
			jPanel21.setLayout(new GridBagLayout());
			jPanel21.setBackground(new Color(238, 238, 238));
			jPanel21.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.lightGray));
			jPanel21.add(getJPanel3(), gridBagConstraints9);
			jPanel21.add(jLabel7, gridBagConstraints10);
			jPanel21.add(jLabel8, gridBagConstraints111);
		}
		return jPanel21;
	}

	/**
	 * 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);
			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="18,10"
