/*
 * Clase creada por Martin, modificada para su integracion con la herramienta.
 *
 *
 */

package com.uvigo.tMaestro.SCOCreator.tool.properties.cellEditors.contentEditors;

import com.uvigo.tMaestro.SCOCreator.tool.MainFrame;


import java.awt.*;
import java.beans.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.xml.bind.*;
import com.uvigo.mhp.xml.multiPanel.*;



public class MultiPanelContentEditorPanel extends JPanel implements ContentEditorPanel {
    private DefaultTableModel tableModel;
    
    private JAXBContext jc;
    private ObjectFactory objFactory;
    private MultiPanelConfiguration configuration;
    private java.util.List elements;
    
    //Ruta hasta el directorio de la aplicacion
    private String sBase;
    
    //Nombre del fichero .xml
    private String sFile;
    
    
    //Ruta al directorio del componente (dentro del directorio del proyecto). Desde /Projects
    private String sDir;
    
    /**
     * Referencia al dialogo que va a contener este panel
     */
    private ContentEditorDialog oDialog;
    
   
    /**
     * Constructor
     * @param sPathFile Ruta relativa al directorio de la aplicacion, del fichero .xml
     * @param oDialog Referencia al dialogo contenedor de este panel.
     */
    public MultiPanelContentEditorPanel(String sPathFile,ContentEditorDialog oDialog) {
        if ((sPathFile==null)||(sPathFile.isEmpty()))  sPathFile = "RESOURCES/MultiPanelCE.xml";//M: inicializacion
      
         initComponents();
        this.oDialog=oDialog;
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
            
        },
                new String [] {
            MainFrame.oMainFrame.getMessage("Title25"),
                    MainFrame.oMainFrame.getMessage("Title26")
        }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        
        
        jButton10.setText(MainFrame.oMainFrame.getMessage("Button7"));
        jButton12.setText(MainFrame.oMainFrame.getMessage("Button6"));
        try {
            jc=JAXBContext.newInstance("com.uvigo.mhp.xml.multiPanel");
            objFactory = new ObjectFactory();
            configuration=objFactory.createMultiPanelConfiguration();
            elements=configuration.getElement();
            
            tableModel=(DefaultTableModel) jTable1.getModel();
            jScrollPane2.getViewport().setBackground(Color.white);
            jScrollPane2.getViewport().setOpaque(true);
            
            
             sBase= new String (MainFrame.oMainFrame.sDir+ "/"); 
            sDir= new String("TEMP/COMPONENTS/");
            
            if (sPathFile!=null) {
                String[] split = sPathFile.split("/");
                
                //Parte de sPathFile que corresponde al fichero
                sFile = split[split.length-1];
                
                
                load(new java.io.File(sBase+sPathFile));
               
            }
            
        } catch (JAXBException ex) {
            System.out.println(ex.getMessage());
        }
        
        
    }
    
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel13 = new javax.swing.JPanel();
        jButton10 = new javax.swing.JButton();
        jButton12 = new javax.swing.JButton();
        jPanel20 = new javax.swing.JPanel();
        jPanel21 = new javax.swing.JPanel();
        jButton17 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setLayout(new java.awt.BorderLayout());

        jPanel13.setLayout(new java.awt.GridLayout(1, 0));

        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });

        jPanel13.add(jButton10);

        jButton12.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton12ActionPerformed(evt);
            }
        });

        jPanel13.add(jButton12);

        add(jPanel13, java.awt.BorderLayout.SOUTH);

        jPanel20.setLayout(new java.awt.BorderLayout());

        jPanel21.setLayout(new java.awt.GridLayout(1, 0));

        jButton17.setText("+");
        jButton17.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton17ActionPerformed(evt);
            }
        });

        jPanel21.add(jButton17);

        jButton1.setText("-");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanel21.add(jButton1);

        jPanel20.add(jPanel21, java.awt.BorderLayout.SOUTH);

        jPanel1.setLayout(new java.awt.BorderLayout());

        jScrollPane2.setAutoscrolls(true);
        jTable1.setCellSelectionEnabled(true);
        jTable1.setEditingColumn(1);
        jTable1.setEditingRow(1);
        jTable1.setOpaque(false);
        jScrollPane2.setViewportView(jTable1);

        jPanel1.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jPanel2.setLayout(new java.awt.GridLayout(0, 1));

        jButton2.setText("<");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jPanel2.add(jButton2);

        jButton3.setText(">");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jPanel2.add(jButton3);

        jPanel1.add(jPanel2, java.awt.BorderLayout.WEST);

        jPanel20.add(jPanel1, java.awt.BorderLayout.CENTER);

        add(jPanel20, java.awt.BorderLayout.CENTER);

    }
    // </editor-fold>//GEN-END:initComponents
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton2ActionPerformed
    {//GEN-HEADEREND:event_jButton2ActionPerformed
        // Hay que desplazar una fila hacia arriba
        int i=jTable1.getSelectedRow();
        if (i<=0) return;
        
        tableModel.moveRow(i,i,i-1);
        Object ob1=elements.get(i);
        Object ob2=elements.get(i-1);
        elements.set(i, ob2);
        elements.set(i-1, ob1);
        
        jTable1.setColumnSelectionInterval(0, 0);
        jTable1.setRowSelectionInterval(i-1, i-1);
    }//GEN-LAST:event_jButton2ActionPerformed
    
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton3ActionPerformed
    {//GEN-HEADEREND:event_jButton3ActionPerformed
        // Hay que desplazar una fila hacia abajo
        
        int i=jTable1.getSelectedRow();
        if (i>=tableModel.getRowCount()-1) return;
        
        tableModel.moveRow(i,i,i+1);
        Object ob1=elements.get(i);
        Object ob2=elements.get(i+1);
        elements.set(i, ob2);
        elements.set(i+1, ob1);
        
        jTable1.setColumnSelectionInterval(0, 0);
        jTable1.setRowSelectionInterval(i+1, i+1);
    }//GEN-LAST:event_jButton3ActionPerformed
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton1ActionPerformed
    {//GEN-HEADEREND:event_jButton1ActionPerformed
        // eliminar las filas seleccionadas
        
        int i[]=jTable1.getSelectedRows();
        if (i.length==0) return;
        
        for (int j=0;j<i.length;j++) {
            tableModel.removeRow(i[j]-j);
            elements.remove(i[j]-j);
        }
        
        if (jTable1.getRowCount()==0) return;
        if (i[0]==jTable1.getRowCount()) {
            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(i[0]-1, i[0]-1);
        } else {
            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(i[0], i[0]);
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    
    private void jButton17ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton17ActionPerformed
    {//GEN-HEADEREND:event_jButton17ActionPerformed
        // a�adir una fila
        try {
            Object temp[]=new Object[2];
            temp[0]=new String("");
            temp[1]=new String("");
            tableModel.addRow(temp);
            
            ElementType et=objFactory.createElementType();
            et.setContextName("");
            et.setPanelTitle("");
            elements.add(et);
            
            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(jTable1.getRowCount()-1, jTable1.getRowCount()-1);
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_jButton17ActionPerformed
    
    
    /**
     * El usuario ha pulsado sobre cancelar
     */
    private void jButton12ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton12ActionPerformed
    {//GEN-HEADEREND:event_jButton12ActionPerformed
        oDialog.setAction(ContentEditorDialog.CANCEL,null);
        oDialog.dispose();
    }//GEN-LAST:event_jButton12ActionPerformed
    
    private void load(java.io.File file) {
        // hay que cargar el contenido de un fichero XML.
        
        try {
            
            if (file == null) return;
            
            int i=tableModel.getRowCount();
            for (int j=0;j<i;j++)
                tableModel.removeRow(0);
            
            Unmarshaller u=jc.createUnmarshaller();
            u.setValidating(true);
            configuration=(MultiPanelConfiguration) u.unmarshal(new FileInputStream(file));
            elements=configuration.getElement();
            
            for (int k=0;k<elements.size();k++) {
                ElementType et=(ElementType) elements.get(k);
                
                Object temp[]=new Object[2];
                temp[0]=et.getContextName();
                temp[1]=et.getPanelTitle();
                tableModel.addRow(temp);
            }
            
            if (tableModel.getRowCount()==0) return;
            
            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(0, 0);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        
    }
    
    
    /**
     * El usuario ha pulsado sobre el boton OK
     */
    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton10ActionPerformed
    {//GEN-HEADEREND:event_jButton10ActionPerformed
        // Hay que grabar un fichero XML con el contenido creado, en el
        // directorio del proyecto (dentro del directorio de componente).
        // Hay que actualizar los campos de texto a los valores indicados en la tabla.
        try {
            java.io.File oDirComponent = new java.io.File(sBase+sDir);
            oDirComponent.mkdir();
            if (!sFile.contains("(")) sFile = new String("(" + MainFrame.oMainFrame.getPSheet().getSelectedOption() + ")" + 
                            MainFrame.oMainFrame.oGetCapsulaActiva().oGetBean().getName()+".xml");//M: le damos el nombre del componente
            java.io.File oFile = new File(oDirComponent,sFile);
            java.util.ArrayList<java.io.File> oFiles = new java.util.ArrayList<java.io.File>();
            
            for (int i=0;i<tableModel.getRowCount();i++) {
                ElementType et=(ElementType) elements.get(i);
                et.setContextName((String) tableModel.getValueAt(i,0));
                et.setPanelTitle((String) tableModel.getValueAt(i,1));
            }
            
            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            oFiles.add(oFile);
            m.marshal(configuration, new FileOutputStream(oFile));
            MainFrame.oMainFrame.getEditionProperty().putOptionFiles(oFiles, MainFrame.oMainFrame.getPSheet().getSelectedOption());
            oDialog.setAction(ContentEditorDialog.OK,sDir+sFile);
            
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println(ex);
            oDialog.setAction(ContentEditorDialog.CANCEL,null); // Si se produce algun error es como cancelar el proceso
        }
        oDialog.dispose();
    }//GEN-LAST:event_jButton10ActionPerformed
    
    public Dimension getPreferredSize() {
        return new Dimension(600,400);
    }
    
    /**
     * Devuelve los ficheros anadidos
     */
    public java.util.ArrayList<java.io.File> getFiles() {
        return null;
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton12;
    private javax.swing.JButton jButton17;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel20;
    private javax.swing.JPanel jPanel21;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}