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 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 javax.swing.JScrollPane;

import negocio.BloqueConstructivo;

import negocio.Plantilla;
import negocio.Proyecto;
import negocio.VistaPlantilla;


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

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

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

	Principal padrePrincipal;

	private JButton jButton2 = 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_vistas;  //  @jve:decl-index=0:
	
	/**
	 * @param owner
	 */
	public MantenimientoVista(JDialog owner) {
		super(owner);
		initialize();
	}
	
	public MantenimientoVista(Principal owner) {
		super(owner);
		padrePrincipal = 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 VistaPlantilla where id_plantilla ='"+plantilla.getIdPlantilla()+"'").list();
			for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
				VistaPlantilla vista = (VistaPlantilla) iter.next();
				modelo.addElement(vista);
			}
			jList.setModel(modelo);
			tx.commit();
			session.close();
		}	
		catch (Exception exp) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
		
	}

	public void EstadisticasNumeroVistas()
	{
		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 VistaPlantilla where id_plantilla = '"+plantilla.getIdPlantilla()+"'").list();
			numero_vistas= messages.size();
			
			jLabel10.setText(numero_vistas.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() {
		//this.setSize(550, 600);
		padrePrincipal.Tamaño_ventana(this);
		this.setModal(true);
		if (padrePrincipal.idioma.equals("español"))
			this.setTitle("Mantenimiento de vistas");
		else
			this.setTitle("Management of views");
		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();
				EstadisticasNumeroVistas();
			}
		});
		
	}

	/**
	 * 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(97, 36));
			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 gridBagConstraints21 = new GridBagConstraints();
			gridBagConstraints21.gridx = 0;
			gridBagConstraints21.fill = GridBagConstraints.HORIZONTAL;
			gridBagConstraints21.insets = new Insets(5, 5, 5, 5);
			gridBagConstraints21.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 vistas");
			else
				jLabel.setText("List of views"); 
			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(), gridBagConstraints21);
		}
		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(87, 26));
			jButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					NuevaVista ventana = new NuevaVista(MantenimientoVista.this, false);
					ventana.setLocationRelativeTo(MantenimientoVista.this);
					ventana.setVisible(true);
				}
			});
		}
		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(87, 26));
			jButton1.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					
					try{			
						
						int idvista = jList.getSelectedIndex();
						if (idvista==-1){
							if (padrePrincipal.idioma.equals("español"))
								throw new Exception("Error, selecciona una vista de la lista");
							else
								throw new Exception("Error, select a view of the list");
						}
						else{

							VistaPlantilla vista = (VistaPlantilla) modelo.getElementAt(idvista);
							
							int n;
							if (padrePrincipal.idioma.equals("español")){
								n = JOptionPane.showConfirmDialog(
									MantenimientoVista.this, "¿Estás seguro de que quieres borrar la vista '" + vista.getNombre() + "'?",
									"Advertencia",
									JOptionPane.YES_NO_OPTION);
							}
							else {
								n = JOptionPane.showConfirmDialog(
										MantenimientoVista.this, "Are you sure you want to delete the view '" + vista.getNombre() + "'?",
										"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();
								
								int idelemento = padrePrincipal.jList.getSelectedIndex();
								Plantilla plantilla = (Plantilla) padrePrincipal.modelo.getElementAt(idelemento);
	
								//Borramos el objeto y todos los objectos relacionados
								List messages_vistas = session.createQuery("from VistaPlantilla where id_vista_plantilla = '"+vista.getIdVistaPlantilla()+"' AND id_plantilla ='"+plantilla.getIdPlantilla()+"'").list();
								
								Iterator iter = messages_vistas.iterator();
								VistaPlantilla vista_ = (VistaPlantilla) iter.next();
								Transaction tx2 = session.beginTransaction();
								session.delete(vista_);
								tx2.commit();
								
								
								//Borramos el objeto de la lista
								modelo.removeElement(vista);
																																									
								
								actualizaModelo();
								EstadisticasNumeroVistas();
								session.close();
							}
						}	
					}	
					catch (Exception exp) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			});
		}
		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(87, 26));
			jButton2.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent e) {
						try{
							int idvista = jList.getSelectedIndex();
							if (idvista==-1){
								if (padrePrincipal.idioma.equals("español"))
									throw new Exception("Error, selecciona una vista de la lista");
								else
									throw new Exception("Error, select a view of the list");
							}
							else{
								NuevaVista ventana = new NuevaVista(MantenimientoVista.this, true);
								ventana.setLocationRelativeTo(MantenimientoVista.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.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.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.lightGray));
			jPanel2.setBackground(new Color(238, 238, 238));
			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.setLayout(new GridBagLayout());
			jPanel3.setBackground(new Color(238, 238, 238));
			jPanel3.add(jLabel9, gridBagConstraints12);
			jPanel3.add(jLabel10, gridBagConstraints13);
		}
		return jPanel3;
	}

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