package interfaz;
import javax.swing.JPanel;

import java.awt.Component;
import java.awt.Frame;
import java.awt.BorderLayout;
import java.awt.Toolkit;

import javax.swing.JDialog;
import java.awt.GridBagLayout;
import javax.swing.JScrollPane;
import java.awt.Dimension;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;

import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.SwingConstants;

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

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

import com.toedter.calendar.JDateChooser;

import persistencia.UtilidadHibernate;
import sun.awt.DefaultMouseInfoPeer;

import java.awt.Insets;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.swing.BorderFactory;
import javax.swing.event.ListDataListener;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.awt.FlowLayout;

public class VerInstancia extends JDialog {

	private static final long serialVersionUID = 1L;

	private JPanel jContentPane = null;

	private JScrollPane jScrollPane = null;

	public JPanel jPanel1 = null;

	private JLabel jLabel2 = null;
	
	private JList jList = null;
	
	private JTextField jTextField2 = null;
	
	private Integer x=0;  //  @jve:decl-index=0:
	private Integer y=0;  

	private ArrayList<ComponenteBloque> listaComponentes = new ArrayList<ComponenteBloque>();  //  @jve:decl-index=0:
	
	private ArrayList<Object> listaTipos = new ArrayList<Object>();  //  @jve:decl-index=0:

	private MantenimientoBloque padreMantenimientoBloque;
	
	private BloqueConstructivo bloquePadre;

	public DefaultListModel modelolista = new DefaultListModel();
	
	public DefaultListModel modeloListaAñadida = new DefaultListModel();

	private JList lista_copia = new JList();
	
	private DefaultListModel modelo_lista_copia = new DefaultListModel();

	private Instancia instancia_padre;
	
	private boolean desdePrincipal = false;
	
	private Principal padrePrincipal;
	
	

	public VerInstancia(JDialog owner) {
		super(owner);
		initialize();
	}
	

	public VerInstancia(Instancia i, BloqueConstructivo b, MantenimientoBloque pb){
		instancia_padre=i;
		bloquePadre=b;
		padreMantenimientoBloque=pb;
		desdePrincipal=false;
		
		initialize();
	}
	
	public VerInstancia(Instancia i, BloqueConstructivo b, Principal p){
		instancia_padre=i;
		bloquePadre=b;
		desdePrincipal=true;
		padrePrincipal=p;
		
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	
	private void ActualizarListaComponentes(){
		try{
						
			//int indice = padreMantenimientoBloque.jList.getSelectedIndex();
			//BloqueConstructivo bloque = (BloqueConstructivo) padreMantenimientoBloque.modelo.getElementAt(indice);
			

			Session session = UtilidadHibernate.getSessionFactory().openSession();
				Transaction tx = session.beginTransaction();
				
				listaComponentes.clear();
				List messages = session.createQuery("from ComponenteBloque where id_bloque = '"+bloquePadre.getIdBloque()+"' order by posicion asc").list();
				System.out.println("Número de elementos: " + messages.size());
				//JLabel etiquetas[messages.size()] = new JLabel(); 
				for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
					ComponenteBloque componente = (ComponenteBloque) iter.next();
					
					listaComponentes.add(componente);
					//listaTipos.add(campotexto);
												
				}
				tx.commit();
				session.close();				
				
		}	
		catch (Exception exp) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	
	
	private void PintarComponentes(){
		try{
			jPanel1.removeAll();

			Session session = UtilidadHibernate.getSessionFactory().openSession();
				Transaction tx = session.beginTransaction();
				
				List messages = session.createQuery("from ComponenteBloque where id_bloque = '"+instancia_padre.getBloqueConstructivo().getIdBloque()+"' order by posicion asc").list();

				for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
					
					final ComponenteBloque componente = (ComponenteBloque) iter.next();
					JLabel etiqueta = new JLabel();
					etiqueta.setText(componente.getNombre());
					etiqueta.setPreferredSize(new Dimension(130,25));
					etiqueta.setHorizontalAlignment(SwingConstants.RIGHT);
					etiqueta.setToolTipText(componente.getNombre());
					
										
					GridBagConstraints gridBagConstraints = new GridBagConstraints();
					gridBagConstraints.gridx = 0;
					gridBagConstraints.gridy = componente.getPosicion();
					gridBagConstraints.insets = new Insets(5, 15, 0, 0);
					
					jPanel1.add(etiqueta,gridBagConstraints);
					
					List messages2 = null;

					messages2 = session.createQuery("from ComponenteInstancia where id_componente_bloque = '"+componente.getIdComponenteBloque()+"' AND id_instancia = '"+instancia_padre.getIdInstancia()+"'").list();

					Iterator iter2 = messages2.iterator();
					ComponenteInstancia componente_instancia = (ComponenteInstancia) iter2.next();
					
					if (componente.getTipo()==0){
						JTextField campotexto = new JTextField();
						campotexto.setEditable(false);
						campotexto.setPreferredSize(new Dimension(600,25));
						if (componente_instancia.getTexto()!=null)
							campotexto.setText(componente_instancia.getTexto());

						listaTipos.add(campotexto);
												
						GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
						gridBagConstraints2.gridx = 1;
						gridBagConstraints2.gridy = componente.getPosicion();
						gridBagConstraints2.insets = new Insets(5, 15, 0, 5);
						gridBagConstraints2.anchor = GridBagConstraints.WEST;
						
						jPanel1.add(campotexto,gridBagConstraints2);
						
						
					}
					else if (componente.getTipo()==1){

						JList lista = new JList();
						
						DefaultListModel modelo_lista = new DefaultListModel();
						
						lista.setModel(modelo_lista);

												
						GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
						gridBagConstraints2.gridx = 1;
						gridBagConstraints2.gridy = componente.getPosicion();
						gridBagConstraints2.insets = new Insets(5, 0, 0, 0);
						
						lista.setVisibleRowCount( 5 );
						lista.setSelectedIndex(-1);
						ComponenteLista_VerInstancia manejo_copia_listas = null;
						if (desdePrincipal)
							manejo_copia_listas = new ComponenteLista_VerInstancia(jPanel1,componente_instancia,bloquePadre,lista, modelo_lista, 0, padrePrincipal, false);
						else
							manejo_copia_listas = new ComponenteLista_VerInstancia(jPanel1,componente_instancia,bloquePadre,lista, modelo_lista, 0, padreMantenimientoBloque.padrePrincipal, false);
						listaTipos.add(modelo_lista);
						
					}
					else if (componente.getTipo()==2){
						JCheckBox checkbox = new JCheckBox();
						checkbox.setPreferredSize(new Dimension(40,18));
						checkbox.setBackground(new Color(238, 238, 238));
						
						JLabel etiqueta_si = new JLabel();
						if (desdePrincipal){
							if (padrePrincipal.idioma.equals("español"))
								etiqueta_si.setText("Si");
							else
								etiqueta_si.setText("Yes");
						}
						else{
							if (padreMantenimientoBloque.padrePrincipal.idioma.equals("español"))
								etiqueta_si.setText("Si");
							else
								etiqueta_si.setText("Yes");
						}
						
						JPanel panel = new JPanel();
						
						if (componente_instancia.getCheckbox()!= null && componente_instancia.getCheckbox()==1)
							if (desdePrincipal){
								if (padrePrincipal.idioma.equals("español"))
									etiqueta_si.setText("Si");
								else
									etiqueta_si.setText("Yes");
							}
							else{
								if (padreMantenimientoBloque.padrePrincipal.idioma.equals("español"))
									etiqueta_si.setText("Si");
								else
									etiqueta_si.setText("Yes");
							}
						else{
							etiqueta_si.setText("No");
						}
						
						listaTipos.add(checkbox);
						
						GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
						gridBagConstraints2.gridx = 1;
						gridBagConstraints2.gridy = componente.getPosicion();;
						gridBagConstraints2.insets = new Insets(5, 15, 0, 5);
						gridBagConstraints2.anchor = GridBagConstraints.WEST;
						
						panel.add(etiqueta_si);
						panel.setBackground(new Color(238, 238, 238));
						
						jPanel1.add(panel,gridBagConstraints2);
						
						
					}
					else if (componente.getTipo()==3){
						JDateChooser campofecha = new JDateChooser();
						campofecha.setPreferredSize(new Dimension(100,25));
						if (padrePrincipal.idioma.equals("español")){
							campofecha.setLocale(new Locale("es", "", ""));
						}
						else{
							campofecha.setLocale(new Locale("en", "", ""));
						}		
						
						
						SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy/MM/dd");
						String strFecha=null;
						if (componente_instancia.getFecha()!=null)
							strFecha = componente_instancia.getFecha();
						System.out.println("FECHA :" + strFecha);
						if (strFecha!=null)
							campofecha.setDate(formatoDelTexto.parse(strFecha));
						campofecha.setBackground(new Color(238, 238, 238));
						
						listaTipos.add(campofecha);
											
						GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
						gridBagConstraints2.gridx = 1;
						gridBagConstraints2.gridy = componente.getPosicion();
						gridBagConstraints2.insets = new Insets(5, 15, 0, 0);
						gridBagConstraints2.anchor = GridBagConstraints.WEST;
						
						jPanel1.add(campofecha,gridBagConstraints2);
					}
					else if (componente.getTipo()==4 && bloquePadre.getTipo()==1){
						JTextField campotexto = new JTextField();
						campotexto.setEditable(false);
						campotexto.setPreferredSize(new Dimension(600,25));
						
						if (componente_instancia.getPortafolio()!=null){
							campotexto.setText(componente_instancia.getPortafolio());
						}
						listaTipos.add(campotexto);
				
						GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
						gridBagConstraints2.gridx = 1;
						gridBagConstraints2.gridy = componente.getPosicion();
						gridBagConstraints2.insets = new Insets(5, 15, 0, 5);
						gridBagConstraints2.anchor = GridBagConstraints.WEST;
						
						jPanel1.add(campotexto,gridBagConstraints2);
					
					}
//					PUNTUACIÓN MODELO MADUREZ
					else if (componente.getTipo()==4 && bloquePadre.getTipo()==2){
						
						JRadioButton radiobutton = new JRadioButton("1");
						JRadioButton radiobutton2 = new JRadioButton("2");
						JRadioButton radiobutton3 = new JRadioButton("3");
						JRadioButton radiobutton4 = new JRadioButton("4");
						JRadioButton radiobutton5 = new JRadioButton("5");
						
						ButtonGroup grupo= new ButtonGroup();
						grupo.add(radiobutton);
						grupo.add(radiobutton2);
						grupo.add(radiobutton3);
						grupo.add(radiobutton4);
						grupo.add(radiobutton5);
						
						if (componente_instancia.getModeloMadurezPuntuacion()!= null){
							if (componente_instancia.getModeloMadurezPuntuacion()==1)
								radiobutton.setSelected(true);
							else if (componente_instancia.getModeloMadurezPuntuacion()==2)
								radiobutton2.setSelected(true);
							else if (componente_instancia.getModeloMadurezPuntuacion()==3)
								radiobutton3.setSelected(true);
							else if (componente_instancia.getModeloMadurezPuntuacion()==4)
								radiobutton4.setSelected(true);
							else if (componente_instancia.getModeloMadurezPuntuacion()==5)
								radiobutton5.setSelected(true);
						}
						
						ArrayList<JRadioButton> lista_radiobutton = new ArrayList<JRadioButton>();
						lista_radiobutton.add(radiobutton);
						lista_radiobutton.add(radiobutton2);
						lista_radiobutton.add(radiobutton3);
						lista_radiobutton.add(radiobutton4);
						lista_radiobutton.add(radiobutton5);
						
						listaTipos.add(lista_radiobutton);
												
						GridBagConstraints gridBagConstraints_radiobutton = new GridBagConstraints();
						gridBagConstraints_radiobutton.gridx = 1;
						gridBagConstraints_radiobutton.gridy = componente.getPosicion();
						gridBagConstraints_radiobutton.insets = new Insets(5, 15, 0, 5);
						gridBagConstraints_radiobutton.anchor = GridBagConstraints.WEST;
						
						GridBagConstraints gridBagConstraints_radiobutton2 = new GridBagConstraints();
						gridBagConstraints_radiobutton2.gridx = 1;
						gridBagConstraints_radiobutton2.gridy = componente.getPosicion();
						gridBagConstraints_radiobutton2.insets = new Insets(5, 115, 0, 5);
						gridBagConstraints_radiobutton2.anchor = GridBagConstraints.WEST;
						
						GridBagConstraints gridBagConstraints_radiobutton3 = new GridBagConstraints();
						gridBagConstraints_radiobutton3.gridx = 1;
						gridBagConstraints_radiobutton3.gridy = componente.getPosicion();
						gridBagConstraints_radiobutton3.insets = new Insets(5, 215, 0, 5);
						gridBagConstraints_radiobutton3.anchor = GridBagConstraints.WEST;
						
						GridBagConstraints gridBagConstraints_radiobutton4 = new GridBagConstraints();
						gridBagConstraints_radiobutton4.gridx = 1;
						gridBagConstraints_radiobutton4.gridy = componente.getPosicion();
						gridBagConstraints_radiobutton4.insets = new Insets(5, 315, 0, 5);
						gridBagConstraints_radiobutton4.anchor = GridBagConstraints.WEST;
						
						GridBagConstraints gridBagConstraints_radiobutton5 = new GridBagConstraints();
						gridBagConstraints_radiobutton5.gridx = 1;
						gridBagConstraints_radiobutton5.gridy = componente.getPosicion();
						gridBagConstraints_radiobutton5.insets = new Insets(5, 415, 0, 5);
						gridBagConstraints_radiobutton5.anchor = GridBagConstraints.WEST;
						
						jPanel1.add(radiobutton,gridBagConstraints_radiobutton);
						jPanel1.add(radiobutton2,gridBagConstraints_radiobutton2);
						jPanel1.add(radiobutton3,gridBagConstraints_radiobutton3);
						jPanel1.add(radiobutton4,gridBagConstraints_radiobutton4);
						jPanel1.add(radiobutton5,gridBagConstraints_radiobutton5);
					
					}
					//MEDIA PARCIAL MODELO MADUREZ
					else if (componente.getTipo()==5 && bloquePadre.getTipo()==2){
						JTextField campotexto = new JTextField();
						campotexto.setPreferredSize(new Dimension(100,25));
						campotexto.setEditable(false);
						campotexto.setBorder(BorderFactory.createLineBorder(Color.red, 1));
						
						//Obtenemos el número de componentes de tipo Puntuación para el cálculo de la media
						List messages_ = session.createQuery("from ComponenteBloque where id_bloque = '"+bloquePadre.getIdBloque()+"' AND tipo = '4' order by id_bloque asc").list();
						Integer numero_componentes_tipo5 = messages_.size();
						
						if (componente_instancia.getModeloMadurezMediaParcial() != null){
							
							Float total = componente_instancia.getModeloMadurezMediaParcial();
							DecimalFormat formateador = new DecimalFormat("#.##");
							
							campotexto.setText(" " + formateador.format(total).toString() + " / 5");
						}
							
						listaTipos.add(campotexto);
												
						GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
						gridBagConstraints2.gridx = 1;
						gridBagConstraints2.gridy = componente.getPosicion();
						gridBagConstraints2.insets = new Insets(5, 15, 0, 5);
						gridBagConstraints2.anchor = GridBagConstraints.WEST;
						
						jPanel1.add(campotexto,gridBagConstraints2);
						
					}
					//MEDIA GLOBAL MODELO MADUREZ
					else if (componente.getTipo()==6 && bloquePadre.getTipo()==2){
						JTextField campotexto = new JTextField();
						campotexto.setPreferredSize(new Dimension(100,25));
						campotexto.setEditable(false);
						campotexto.setBorder(BorderFactory.createLineBorder(Color.blue, 1));
						
						
						if (componente_instancia.getModeloMadurezMediaGlobal() != null){
							Float total =  componente_instancia.getModeloMadurezMediaGlobal();
							DecimalFormat formateador = new DecimalFormat("#.##");
							
							campotexto.setText(" " + formateador.format(total).toString() + " / 5");
							
						}
						
							
						listaTipos.add(campotexto);
												
						GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
						gridBagConstraints2.gridx = 1;
						gridBagConstraints2.gridy = componente.getPosicion();
						gridBagConstraints2.insets = new Insets(5, 15, 0, 5);
						gridBagConstraints2.anchor = GridBagConstraints.WEST;
						
						jPanel1.add(campotexto,gridBagConstraints2);
						
					}
					else if (componente.getTipo()==7 && bloquePadre.getTipo()==2){
						final JDateChooser campofecha = new JDateChooser();
						campofecha.setPreferredSize(new Dimension(100,25));
						campofecha.setBorder(BorderFactory.createLineBorder(Color.green, 1));
						if (padrePrincipal.idioma.equals("español")){
							campofecha.setLocale(new Locale("es", "", ""));
						}
						else{
							campofecha.setLocale(new Locale("en", "", ""));
						}		
						
						SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy/MM/dd");
						String strFecha=null;
						if (componente_instancia.getFechaModeloMadurez()!=null)
							strFecha = componente_instancia.getFechaModeloMadurez();
						System.out.println("FECHA :" + strFecha);
						if (strFecha!=null)
							campofecha.setDate(formatoDelTexto.parse(strFecha));
						campofecha.setBackground(new Color(238, 238, 238));
						
						listaTipos.add(campofecha);
												
						final GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
						gridBagConstraints2.gridx = 1;
						gridBagConstraints2.gridy = componente.getPosicion();
						gridBagConstraints2.insets = new Insets(5, 15, 0, 5);
						gridBagConstraints2.anchor = GridBagConstraints.WEST;
						
						jPanel1.add(campofecha,gridBagConstraints2);

					}

				}
				tx.commit();
				session.close();
				jPanel1.updateUI();
	
		}	
		catch (Exception exp) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(null, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
		
	}
	
	private void initialize() {
		//this.setSize(1024, 768);
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		this.setSize(d.width,d.height-40);

		this.setModal(true);
		this.setTitle(bloquePadre.getNombre() + " - " + instancia_padre.getNombre());
		this.setContentPane(getJContentPane());
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowOpened(java.awt.event.WindowEvent e) {
				ActualizarListaComponentes();
				PintarComponentes();
			}
		});
	}

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

	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getJPanel1());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jPanel1	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel1() {
		if (jPanel1 == null) {
			jPanel1 = new JPanel();
			jPanel1.setLayout(new GridBagLayout());
			jPanel1.setBackground(new Color(238, 238, 238));
		}
		return jPanel1;
	}

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