package interfaz;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import java.awt.Color;
import java.awt.Frame;
import java.awt.BorderLayout;
import java.awt.SystemColor;

import javax.swing.JDialog;

import com.toedter.calendar.JDateChooser;

import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import java.awt.GridBagConstraints;
import java.awt.FlowLayout;
import javax.swing.JLabel;

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

import persistencia.UtilidadHibernate;

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

import java.awt.Insets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Formatter;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

public class ModeloMadurezPorFechas extends JDialog {

	private static final long serialVersionUID = 1L;

	private JPanel jContentPane = null;
	
	public Principal padrePrincipal;
	
	private JDateChooser fecha_inicial;
	
	private JDateChooser fecha_final;

	private JPanel jPanel = null;

	private JPanel jPanel1 = null;

	private JButton jButton = null;

	private JLabel jLabel = null;

	private JLabel jLabel1 = null;
	
	private int flagInforme;

	private JLabel jLabel2 = null;

	private JLabel jLabel3 = null;
	
	private JScrollPane jScrollPane = null;
	
	private DefaultListModel modelo_jList = new DefaultListModel();;
	
	private DefaultListModel modelo_jList1 = new DefaultListModel();;
	
	private JList jList;

	private JPanel jPanel2 = null;

	private JButton jButton1 = null;

	private JScrollPane jScrollPane1 = null;

	private JList jList1 = null;

	private JPanel jPanel3 = null;

	private JButton jButton2 = null;

	private JLabel jLabel4 = null;
	
	private Plantilla plantillaPadre;
	

	/**
	 * @param owner
	 */
	public ModeloMadurezPorFechas(Principal principal, int flag, Plantilla p) {
		super(principal);
		padrePrincipal = principal;
		flagInforme = flag;
		plantillaPadre = p;
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(691, 381);
		this.setModal(true);
		this.setContentPane(getJContentPane());
		if (flagInforme == 0){
			if (padrePrincipal.idioma.equals("español"))
				this.setTitle("Informe de modelo de madurez por fechas");
			else
				this.setTitle("Report madurity model by dates");
		}
		else if (flagInforme == 1){
			if (padrePrincipal.idioma.equals("español"))
				this.setTitle("Media parcial de modelo de madurez por fechas");
			else
				this.setTitle("Partial average madurity model by dates");
		}
		else{
			if (padrePrincipal.idioma.equals("español"))
				this.setTitle("Media global de modelo de madurez por fechas");
			else
				this.setTitle("Global average madurity model by dates");
		}
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowOpened(java.awt.event.WindowEvent e) {
				if (flagInforme==2){
					ModeloMadurezPorFechas.this.setSize(500, 200);
				}
				else{
					ListaBloquesTipoModeloMadurez();
				}
			}
		});
	}

	void ListaBloquesTipoModeloMadurez(){
		
		Session session = UtilidadHibernate.getSessionFactory().openSession();
		
		Transaction tx = session.beginTransaction();
		
		modelo_jList.removeAllElements();
		List messages = session.createQuery("from BloqueConstructivo m where id_plantilla = '"+plantillaPadre.getIdPlantilla()+"' AND tipo = 2 order by nombre asc").list();
		for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
			BloqueConstructivo bloque = (BloqueConstructivo) iter.next();
			modelo_jList.addElement(bloque);
			
		}
		jList.setModel(modelo_jList);
		tx.commit();
		session.close();
		
	}
	
	/**
	 * 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.add(getJButton(), null);
			jPanel.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.lightGray));
			jPanel.setBackground(SystemColor.controlHighlight);
		}
		return jPanel;
	}

	/**
	 * This method initializes jPanel1	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel1() {
		if (jPanel1 == null) {
			GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
			gridBagConstraints5.gridwidth = 4;
			gridBagConstraints5.gridy = 4;
			gridBagConstraints5.insets = new Insets(10, 20, 10, 0);
			gridBagConstraints5.gridheight = 2;
			gridBagConstraints5.ipadx = 0;
			gridBagConstraints5.fill = GridBagConstraints.VERTICAL;
			gridBagConstraints5.ipady = 0;
			gridBagConstraints5.gridx = 0;
			GridBagConstraints gridBagConstraints22 = new GridBagConstraints();
			gridBagConstraints22.gridx = 0;
			gridBagConstraints22.gridwidth = 2;
			gridBagConstraints22.anchor = GridBagConstraints.WEST;
			gridBagConstraints22.insets = new Insets(20, 0, 0, 0);
			gridBagConstraints22.gridy = 3;
			jLabel3 = new JLabel();
			if (padrePrincipal.idioma.equals("español")){
				jLabel3.setText("Filtro por bloque constructivo:");
				jLabel3.setToolTipText("Si la lista situada a la derecha está vacía, el sistema filtrará todos los bloques contructivos.");
			}
			else{
				jLabel3.setText("Filter by building block:");
				jLabel3.setToolTipText("If the list on the right is empty, the system will filter all building blocks.");
			}
			GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
			gridBagConstraints11.gridx = 0;
			gridBagConstraints11.fill = GridBagConstraints.HORIZONTAL;
			gridBagConstraints11.ipadx = 0;
			gridBagConstraints11.gridwidth = 2;
			gridBagConstraints11.gridy = 0;
			jLabel2 = new JLabel();
			if (padrePrincipal.idioma.equals("español")){
				jLabel2.setText("Filtro por fecha:");
				jLabel2.setToolTipText("Si la fecha inicial está vacía el sistema filtrará por la fecha más antigua. Si la fecha final está vacía, el sistema filtrará por la fecha más reciente.");
			}
			else{
				jLabel2.setText("Filter by date:");
				jLabel2.setToolTipText("If the initial date is empty, the system will filter by the earliest date. If the final date is empty, the system will filter by the most recent date.");
			}
			
			GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
			gridBagConstraints21.gridx = 1;
			gridBagConstraints21.insets = new Insets(10, 0, 0, 150);
			gridBagConstraints21.fill = GridBagConstraints.HORIZONTAL;
			gridBagConstraints21.gridwidth = 2;
			gridBagConstraints21.gridy = 2;
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.gridx = 0;
			gridBagConstraints1.insets = new Insets(10, 20, 0, 10);
			gridBagConstraints1.anchor = GridBagConstraints.WEST;
			gridBagConstraints1.gridy = 2;
			jLabel1 = new JLabel();
			if (padrePrincipal.idioma.equals("español"))
				jLabel1.setText("Fecha final:");
			else
				jLabel1.setText("Final date:");
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = 0;
			gridBagConstraints.insets = new Insets(10, 20, 0, 10);
			gridBagConstraints.anchor = GridBagConstraints.WEST;
			gridBagConstraints.gridy = 1;
			GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
			gridBagConstraints2.insets = new Insets(10, 0, 0, 150);
			gridBagConstraints2.gridx = 1;
			gridBagConstraints2.fill = GridBagConstraints.HORIZONTAL;
			gridBagConstraints2.gridwidth = 1;
			gridBagConstraints2.gridy = 1;
			fecha_inicial = new JDateChooser();
			if (padrePrincipal.idioma.equals("español"))
				fecha_inicial.setLocale(new Locale("es", "", ""));
			else
				fecha_inicial.setLocale(new Locale("en", "", ""));
			
			fecha_final = new JDateChooser();
			if (padrePrincipal.idioma.equals("español"))
				fecha_final.setLocale(new Locale("es", "", ""));
			else
				fecha_final.setLocale(new Locale("en", "", ""));
			jLabel = new JLabel();
			if (padrePrincipal.idioma.equals("español"))
				jLabel.setText("Fecha inicial:");
			else
				jLabel.setText("Initial date:");
			jPanel1 = new JPanel();
			jPanel1.setLayout(new GridBagLayout());
			jPanel1.setPreferredSize(new Dimension(380, 300));
			jPanel1.add(jLabel, gridBagConstraints);
			jPanel1.add(fecha_inicial, gridBagConstraints2);
			jPanel1.add(fecha_final, gridBagConstraints21);
			jPanel1.add(jLabel1, gridBagConstraints1);
			jPanel1.add(jLabel2, gridBagConstraints11);
			if (flagInforme !=2){
				jPanel1.add(jLabel3, gridBagConstraints22);
				jPanel1.add(getJPanel2(), gridBagConstraints5);
			}
		}
		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("Aceptar");
			else
				jButton.setText("Accept");
			jButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					String fecha_ini = null;
					String fecha_fin = null;
					
					
					try{
						////////////////
						////*FECHAS*////
						////////////////
						if (Color.RED == fecha_inicial.getDateEditor().getUiComponent().getForeground()){
							if (padrePrincipal.idioma.equals("español"))
								throw new Exception ("Error, formato de fecha inicial incorrecto.");
							else
								throw new Exception ("Error, Wrong initial date format.");
						}
						else if (Color.RED == fecha_final.getDateEditor().getUiComponent().getForeground()){
							if (padrePrincipal.idioma.equals("español"))
								throw new Exception ("Error, formato de fecha final incorrecto.");
							else
								throw new Exception ("Error, Wrong final date format.");
						}
						
						//FECHA INICIAL
						if (fecha_inicial.getDate()==null){
//							Comprobar que existe el componente fecha
							Session session = UtilidadHibernate.getSessionFactory().openSession();
							
							int id_proyecto = padrePrincipal.jList.getSelectedIndex();
							Proyecto proyecto = (Proyecto) padrePrincipal.modelo.getElementAt(id_proyecto);
							
							ArrayList<String> lista_fechas = new ArrayList<String>();
							List messages = session.createQuery("from Instancia where id_proyecto = '"+proyecto.getIdProyecto()+"'").list();
								for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
									Instancia instancia = (Instancia) iter.next();
									
									List messages2 = session.createQuery("from ComponenteInstancia where id_instancia = '"+instancia.getIdInstancia()+"' and fecha_modelo_madurez is not null order by fecha_modelo_madurez").list();
									for ( Iterator iter2 = messages2.iterator(); iter2.hasNext(); ) {
										ComponenteInstancia componente_instancia = (ComponenteInstancia) iter2.next();
										
										if (!lista_fechas.contains(componente_instancia.getFechaModeloMadurez()))
											lista_fechas.add(componente_instancia.getFechaModeloMadurez());
									}
								}
								if (!lista_fechas.isEmpty())
									fecha_ini = lista_fechas.get(0);
							
						}
						else{
							//FECHA INICIAL
							int a_ini = fecha_inicial.getCalendar().get(Calendar.YEAR);
							int b_ini = 1+(fecha_inicial.getCalendar().get(Calendar.MONTH));
							int c_ini = fecha_inicial.getCalendar().get(Calendar.DAY_OF_MONTH);
							
							Formatter fmt_dia_ini = new Formatter();
							fmt_dia_ini.format("%1$02d",c_ini);
							
							Formatter fmt_mes_ini = new Formatter();
							fmt_mes_ini.format("%1$02d",b_ini);
	
							Formatter fmt_anyo_ini = new Formatter();
							fmt_anyo_ini.format("%1$04d",a_ini);
							
							fecha_ini = fmt_anyo_ini + "/" + fmt_mes_ini + "/" + fmt_dia_ini;
						}
						
						//FECHA FINAL
						if (fecha_final.getDate()==null){
//							Comprobar que existe el componente fecha
							Session session = UtilidadHibernate.getSessionFactory().openSession();
							
							int id_proyecto = padrePrincipal.jList.getSelectedIndex();
							Proyecto proyecto = (Proyecto) padrePrincipal.modelo.getElementAt(id_proyecto);
							
							ArrayList<String> lista_fechas = new ArrayList<String>();
							List messages = session.createQuery("from Instancia where id_proyecto = '"+proyecto.getIdProyecto()+"'").list();
								for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
									Instancia instancia = (Instancia) iter.next();
									
									List messages2 = session.createQuery("from ComponenteInstancia where id_instancia = '"+instancia.getIdInstancia()+"' and fecha_modelo_madurez is not null order by fecha_modelo_madurez").list();
									for ( Iterator iter2 = messages2.iterator(); iter2.hasNext(); ) {
										ComponenteInstancia componente_instancia = (ComponenteInstancia) iter2.next();
										
										if (!lista_fechas.contains(componente_instancia.getFechaModeloMadurez()))
											lista_fechas.add(componente_instancia.getFechaModeloMadurez());
									}
								}
								
								if (!lista_fechas.isEmpty())
									fecha_fin = lista_fechas.get(lista_fechas.size()-1);
							
						}else{
							//FECHA FINAL
//							System.out.println( ((JDateChooser)listaTipos.get(i)).getCalendar().getTime() );
							int a_fin = fecha_final.getCalendar().get(Calendar.YEAR);
							int b_fin = 1+(fecha_final.getCalendar().get(Calendar.MONTH));
							int c_fin = fecha_final.getCalendar().get(Calendar.DAY_OF_MONTH);
							
							Formatter fmt_dia_fin = new Formatter();
							fmt_dia_fin.format("%1$02d",c_fin);
							
							Formatter fmt_mes_fin = new Formatter();
							fmt_mes_fin.format("%1$02d",b_fin);
	
							Formatter fmt_anyo_fin = new Formatter();
							fmt_anyo_fin.format("%1$04d",a_fin);
							
							fecha_fin = fmt_anyo_fin + "/" + fmt_mes_fin + "/" + fmt_dia_fin;
							
						}
						
						////////////////
						////*BLOQUES*///
						////////////////
						ArrayList<BloqueConstructivo> listaBloques = new ArrayList<BloqueConstructivo>();
						for (int i = 0; i<modelo_jList1.getSize(); i++){
							BloqueConstructivo bloque = (BloqueConstructivo) modelo_jList1.get(i);
							listaBloques.add(bloque);
						}
						
						
						ModeloMadurezPorFechas.this.dispose();
						if (flagInforme == 0)
							padrePrincipal.Informe_modelo_madurez(fecha_ini,fecha_fin, listaBloques);
						else if (flagInforme == 1)
							padrePrincipal.Grafico_modelo_madurez_parcial(fecha_ini,fecha_fin, listaBloques);
						else
							padrePrincipal.Grafico_modelo_madurez_global(fecha_ini,fecha_fin, listaBloques);
					}
					catch (Exception exp) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
						//JOptionPane.showMessageDialog(null, "Error, el formato de la fecha no es válido.", "Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			});
		}
		return jButton;
	}
	
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setPreferredSize(new Dimension(150, 160));
			jScrollPane.setViewportView(getJList());
		}
		return jScrollPane;
	}
	
	private JList getJList() {
		if (jList == null) {
			jList = new JList();
			jList.setVisibleRowCount( 10 );
			jList.setSelectionMode(
			        ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
			jList.setModel(modelo_jList);
		}
		return jList;
	}

	/**
	 * This method initializes jPanel2	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel2() {
		if (jPanel2 == null) {
			jPanel2 = new JPanel();
			jPanel2.setLayout(new FlowLayout());
			jPanel2.add(getJScrollPane(), null);
			jPanel2.add(getJButton1(), null);
			jPanel2.add(getJScrollPane1(), null);
			jPanel2.add(getJPanel3(), null);
		}
		return jPanel2;
	}

	/**
	 * 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("Añadir >>>");
			else
				jButton1.setText("Add >>>");
			jButton1.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					
					int elemento = jList.getSelectedIndex();
	            	if (elemento == -1){
	            		if (padrePrincipal.idioma.equals("español"))
	            			JOptionPane.showMessageDialog(null, "Selecciona un bloque constructivo de la lista", "Error", JOptionPane.ERROR_MESSAGE);
	            		else
	            			JOptionPane.showMessageDialog(null, "Select a building block of the list", "Error", JOptionPane.ERROR_MESSAGE);
	            	}
	            	else if (modelo_jList1.size()>=10){
	            		if (padrePrincipal.idioma.equals("español"))
	            			JOptionPane.showMessageDialog(null, "Excede de la cardinalidad máxima permitida en la lista: 10 elementos", "Error", JOptionPane.ERROR_MESSAGE);
	            		else
	            			JOptionPane.showMessageDialog(null, "The list exceeds the maximum allowed cardinality: 10 elements", "Error", JOptionPane.ERROR_MESSAGE);
	            	}
	            	else{
	            		BloqueConstructivo bloque = (BloqueConstructivo) modelo_jList.getElementAt(elemento);
	            		modelo_jList1.addElement(bloque);
	            		
	            		modelo_jList.removeElement(bloque);

	            	}
				}
			});
		}
		return jButton1;
	}

	/**
	 * This method initializes jScrollPane1	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane1() {
		if (jScrollPane1 == null) {
			jScrollPane1 = new JScrollPane();
			jScrollPane1.setPreferredSize(new Dimension(150, 160));
			jScrollPane1.setViewportView(getJList1());
		}
		return jScrollPane1;
	}

	/**
	 * This method initializes jList1	
	 * 	
	 * @return javax.swing.JList	
	 */
	private JList getJList1() {
		if (jList1 == null) {
			jList1 = new JList();
			jList1.setVisibleRowCount(10);
			jList1.setSelectionMode(
			        ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
			jList1.setModel(modelo_jList1);
		}
		return jList1;
	}

	/**
	 * This method initializes jPanel3	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel3() {
		if (jPanel3 == null) {
			jLabel4 = new JLabel();
			jLabel4.setText("Max. 10");
			jPanel3 = new JPanel();
			jPanel3.setLayout(new FlowLayout());
			jPanel3.setPreferredSize(new Dimension(80, 80));
			jPanel3.add(getJButton2(), null);
			jPanel3.add(jLabel4, null);
		}
		return jPanel3;
	}

	/**
	 * 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("Eliminar");
			else
				jButton2.setText("Delete");
			jButton2.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					
            		int elemento = jList1.getSelectedIndex();
                	if (elemento != -1){
                		BloqueConstructivo bloque = (BloqueConstructivo) modelo_jList1.getElementAt(elemento);
                		modelo_jList1.removeElement(bloque);
                		modelo_jList.addElement(bloque);
                	}
				}
			});
		}
		return jButton2;
	}

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