package interfaz;

import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JDialog;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import negocio.BloqueConstructivo;
import negocio.ComponenteBloque;
import negocio.ComponenteInstancia;
import negocio.Instancia;
import negocio.Plantilla;

import org.hibernate.Session;
import org.hibernate.Transaction;
import com.sun.crypto.provider.DESedeCipher;

import persistencia.UtilidadHibernate;

import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.SystemColor;
import java.util.Iterator;
import java.util.List;
import java.awt.Color;
import javax.swing.BorderFactory;
import java.awt.Dimension;

public class ModificarComponente 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 JLabel jLabel = null;

	private JTextField jTextField = null;
	
	public MantenimientoInstancia padreMantenimientoInstancia = null;

	private boolean desdePrincipal=false;
	
	private EditorDeBloques padreEditorDeBloques;
	
	private ComponenteBloque componente;
	
	public String idioma;
	/**
	 * @param owner
	 */
	public ModificarComponente(EditorDeBloques owner, ComponenteBloque c) {
		super(owner);
		padreEditorDeBloques = owner;
		componente = c;
		idioma=padreEditorDeBloques.idioma;
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(550, 250);
		this.setModal(true);
		if (idioma.equals("español"))
			this.setTitle("Modificar componente");
		else
			this.setTitle("Modify component");
		this.setContentPane(getJContentPane());
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowOpened(java.awt.event.WindowEvent e) {
				jTextField.setText(componente.getNombre());
			}
		});
	}

	/**
	 * 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.setBackground(SystemColor.controlHighlight);
			jPanel.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.lightGray));
			jPanel.add(getJButton(), null);
		}
		return jPanel;
	}

	/**
	 * This method initializes jPanel1	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel1() {
		if (jPanel1 == null) {
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.fill = GridBagConstraints.BOTH;
			gridBagConstraints1.gridy = 0;
			gridBagConstraints1.weightx = 1.0;
			gridBagConstraints1.anchor = GridBagConstraints.WEST;
			gridBagConstraints1.insets = new Insets(0, 5, 0, 20);
			gridBagConstraints1.gridx = 1;
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = 0;
			gridBagConstraints.insets = new Insets(0, 20, 0, 0);
			gridBagConstraints.gridy = 0;
			jLabel = new JLabel();
			if (idioma.equals("español"))
				jLabel.setText("Nombre:");
			else
				jLabel.setText("Name:");
			jPanel1 = new JPanel();
			jPanel1.setLayout(new GridBagLayout());
			jPanel1.setBackground(new Color(238, 238, 238));
			jPanel1.add(jLabel, gridBagConstraints);
			jPanel1.add(getJTextField(), gridBagConstraints1);
			
		}
		return jPanel1;
	}

	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton() {
		if (jButton == null) {
			jButton = new JButton();
			if (idioma.equals("español"))
				jButton.setText("Aceptar");
			else
				jButton.setText("Accept");
			jButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					String nombre;
					
					try{
						if((nombre=jTextField.getText().trim()).length()<=0)
							if(idioma.equals("español"))
								throw new Exception("El nombre está vacío.");
							else
								throw new Exception("The name is empty.");
						else{
							
							Session session=null;
							
							session = UtilidadHibernate.getSessionFactory().openSession();

							//Comprobamos que el nombre del componente no se repita en la base de datos.
							List messages = session.createQuery("from ComponenteBloque where nombre ='"+nombre+"' AND id_bloque='"+padreEditorDeBloques.ObtenerBloque(padreEditorDeBloques.desdePrincipal).getIdBloque()+"'").list();
							if (messages.size() <= 0 || (messages.size()==1 && jTextField.getText().equals(componente.getNombre()))){
							
								//Cambiamos el componente del bloque seleccionado
								List messages2 = session.createQuery("from ComponenteBloque where nombre ='"+componente.getNombre()+"' AND tipo='"+componente.getTipo()+"' AND orden='"+componente.getOrden()+"' AND id_bloque='"+padreEditorDeBloques.ObtenerBloque(padreEditorDeBloques.desdePrincipal).getIdBloque()+"'").list();
								for (Iterator iter = messages2.iterator(); iter.hasNext(); ){
									Transaction tx = session.beginTransaction();
									
									ComponenteBloque comp = (ComponenteBloque) iter.next();
									comp.setNombre(nombre);
									session.update(comp);
									tx.commit();
								}

								padreEditorDeBloques.jPanel1.updateUI();
							}
							else{
								if (idioma.equals("español"))
									throw new Exception ("Error, ya existe un componente con ese nombre");
								else
									throw new Exception ("Error, There is already a component with that name");
							}
							session.close();
							
							//JOptionPane.showMessageDialog(null, "El proyecto se ha dado de alta correctamente, el responsable de proyecyo podrá modificarlos para añadirle los participantes y los participantes externos", "Información", JOptionPane.INFORMATION_MESSAGE);
							ModificarComponente.this.dispose();
						}
					}	
					catch (Exception exp) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			});
		}
		return jButton;
	}

	/**
	 * This method initializes jTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextField() {
		if (jTextField == null) {
			jTextField = new JTextField();
		}
		return jTextField;
	}

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