/*
 * Clase creada por Martin, modificada para su integraci�n con la herramienta.
 *
 *
 */



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

import com.uvigo.tMaestro.SCOCreator.tool.MainFrame;
import com.uvigo.tMaestro.SCOCreator.tool.MyFileFilter;
import com.uvigo.tMaestro.SCOCreator.tool.ImageView;
import com.uvigo.tMaestro.SCOCreator.tool.MyOptionPane;


import com.uvigo.mhp.ui.*;
import com.uvigo.mhp.xml.animation.*;
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 org.havi.ui.*;

// Soportar clics en la galeria.
// Usar como muestra una animacion algo mas lenta, no ciclica...

public class AnimatedContentEditorPanel extends JPanel implements ContentEditorPanel{
    private DefaultTableModel tableModel;
    
    private JAXBContext jc;
    private ObjectFactory objFactory;
    
    private MediaTracker trk;
    private Vector images;
    
    
    //Ruta hasta el directorio de la aplicacion
    private String sBase;
    
    //Ruta desde sBase hasta el directorio en donde esta el fichero xml
    private String sRuta;
    
    //Nombre del fichero .xml
    private String sFile;
    
    //Listado de ficheros a�adidos desde este panel en algun momento.
    //Guarda tanto los actuales como los descartados
    private java.util.ArrayList<java.io.File> oAddedFiles=new  java.util.ArrayList<java.io.File>();
    
    //Ruta al directorio del componente (dentro del directorio del proyecto). Desde /Projects
    private String sDir;
    
    /**
     * Referencia al di�logo que va a contener este panel
     */
    private ContentEditorDialog oDialog;
  
    /**
     * Constructor
     * @param sPathFile Ruta relativa al directorio de la aplicaciOn, del fichero .xml
     * @param oDialog Referencial al dialogo contenedor de este panel.
     */
    public AnimatedContentEditorPanel(String sPathFile,ContentEditorDialog oDialog) {
        if ((sPathFile==null)||(sPathFile.isEmpty())) sPathFile = "RESOURCES/AnimatedCE.xml";//M: inicializacion
      
         initComponents();
        this.oDialog=oDialog;
        jButton10.setText(MainFrame.oMainFrame.getMessage("Button7"));
        jButton12.setText(MainFrame.oMainFrame.getMessage("Button6"));
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
            
        },
                new String [] {
            MainFrame.oMainFrame.getMessage("Title22")
        }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };
            
            boolean[] canEdit = new boolean [] {false};
            
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
            
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        try {
            jc=JAXBContext.newInstance("com.uvigo.mhp.xml.animation");
            objFactory = new ObjectFactory();
            tableModel=(DefaultTableModel) jTable1.getModel();
            trk=new MediaTracker(this);
            images=new Vector();
            jScrollPane2.getViewport().setBackground(Color.white);
            jScrollPane2.getViewport().setOpaque(true);
            hAnimated1.setRepeatCount(1);
            hAnimated1.setPlayMode(HAnimation.PLAY_REPEATING);
            
            //M: ahora..
             sBase= new String (MainFrame.oMainFrame.sDir+ "/");
            sDir= new String("TEMP/COMPONENTS/");
            
            if (sPathFile!=null) {
                //Parte de sPathFile que corresponde a ruta (que no es fichero)
                String[] split = sPathFile.split("/");
                sRuta=new String();
                int z=0;
                for (z=0;z<split.length-1;z++) {
                    sRuta = sRuta.concat(split[z]+"/");
                }
                
                //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();
        jSplitPane1 = new javax.swing.JSplitPane();
        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();
        jPanel22 = new javax.swing.JPanel();
        jPanel14 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jPanel3 = new javax.swing.JPanel();
        jPanel17 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        hAnimated1 = new com.uvigo.mhp.ui.HAnimated();
        jPanel18 = new javax.swing.JPanel();
        jButton15 = new javax.swing.JButton();
        jButton16 = 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);

        jSplitPane1.setDividerLocation(150);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        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);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });

        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);

        jSplitPane1.setTopComponent(jPanel20);

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

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

        jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.X_AXIS));

        jScrollPane3.setViewportView(jPanel3);

        jPanel14.add(jScrollPane3, java.awt.BorderLayout.CENTER);

        jPanel22.add(jPanel14);

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

        jScrollPane4.setViewportView(hAnimated1);

        jPanel17.add(jScrollPane4, java.awt.BorderLayout.CENTER);

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

        jButton15.setText("PLAY");
        jButton15.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton15ActionPerformed(evt);
            }
        });

        jPanel18.add(jButton15);

        jButton16.setText("STOP");
        jButton16.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton16ActionPerformed(evt);
            }
        });

        jPanel18.add(jButton16);

        jPanel17.add(jPanel18, java.awt.BorderLayout.SOUTH);

        jPanel22.add(jPanel17);

        jSplitPane1.setRightComponent(jPanel22);

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

    }
    // </editor-fold>//GEN-END:initComponents
    
    private void jButton16ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton16ActionPerformed
    {//GEN-HEADEREND:event_jButton16ActionPerformed
        hAnimated1.stop();
    }//GEN-LAST:event_jButton16ActionPerformed
    
    private void jButton15ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton15ActionPerformed
    {//GEN-HEADEREND:event_jButton15ActionPerformed
        Image temp[]=new Image[images.size()];
        images.copyInto(temp);
        hAnimated1.setAnimateContent(temp,HState.ALL_STATES);
        hAnimated1.start();
    }//GEN-LAST:event_jButton15ActionPerformed
    
    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);
        
        // No es necesario mover los elementos de locators porque estos
        // se actualizan al grabar el fichero XML.
        
        Object ob1=images.get(i);
        Object ob2=images.get(i-1);
        images.set(i, ob2);
        images.set(i-1, ob1);
        
        jTable1.setColumnSelectionInterval(0, 0);
        jTable1.setRowSelectionInterval(i-1, i-1);
        
        updateGallery();
    }//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=images.get(i);
        Object ob2=images.get(i+1);
        images.set(i, ob2);
        images.set(i+1, ob1);
        
        jTable1.setColumnSelectionInterval(0, 0);
        jTable1.setRowSelectionInterval(i+1, i+1);
        
        updateGallery();
    }//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);
            images.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]);
        }
        
        updateGallery();
    }//GEN-LAST:event_jButton1ActionPerformed
    
    private void jButton17ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton17ActionPerformed
    {//GEN-HEADEREND:event_jButton17ActionPerformed
        // Insertar una fila
        
        javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
        MyFileFilter oFilter = new MyFileFilter();
        oFilter.vAddExtension("jpeg");
        oFilter.vAddExtension("jpg");
        oFilter.vSetDescripcion(".jpeg");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("gif");
        oFilter.vSetDescripcion(".gif");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("png");
        oFilter.vSetDescripcion(".png");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("tif");
        oFilter.vAddExtension("tiff");
        oFilter.vSetDescripcion(".tiff");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("tif");
        oFilter.vAddExtension("tiff");
        oFilter.vAddExtension("jpeg");
        oFilter.vAddExtension("jpg");
        oFilter.vAddExtension("png");
        oFilter.vAddExtension("gif");
        oFilter.vSetDescripcion(".jpeg .tiff .gif .png");
        chooser.addChoosableFileFilter(oFilter);
        chooser.setAccessory(new ImageView(chooser));
        chooser.setCurrentDirectory(MainFrame.oMainFrame.getLastDir());
        boolean bExit=false;
        while (!bExit){
            int option = chooser.showOpenDialog(this);
            if (option == javax.swing.JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
             //Si existe un fichero con el mismo nombre entre los elementos que el usuario ha configurado, lo avisamos
                if (new java.io.File(sBase+sDir, file.getName()).exists()) {
                    int iOption = MyOptionPane.showConfirmDialog(MainFrame.oMainFrame,MainFrame.oMainFrame.getMessage("Question4"),MainFrame.oMainFrame.getMessage("Title2"),javax.swing.JOptionPane.YES_NO_OPTION,javax.swing.JOptionPane.WARNING_MESSAGE);
                    if (iOption==javax.swing.JOptionPane.NO_OPTION) continue;
                }
                
                bExit=true;
                try {
                    setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
                    MainFrame.oMainFrame.setLastDir(file.getParentFile());
                    
                    java.io.File oDirComponent = new java.io.File(sBase+sDir);
                    oDirComponent.mkdir();
                    
                    
                    java.io.File oImage =  new java.io.File(oDirComponent,file.getName());
                    MainFrame.copyFile(file,oImage);
                    oAddedFiles.add(oImage);
                    
                    
                    URL url=new URL("file:/"+sBase+sDir+file.getName());
                    Image img=Toolkit.getDefaultToolkit().getImage(url);
                    trk.addImage(img,0);
                    trk.waitForAll();
                    
                    images.add(img);
                    Object temp[]=new Object[1];
                    temp[0]=file.getName();
                    
                    tableModel.addRow(temp);
                    jTable1.setColumnSelectionInterval(0, 0);
                    jTable1.setRowSelectionInterval(jTable1.getRowCount()-1, jTable1.getRowCount()-1);
                    
                    HImage himg=new HImage();
                    updateGallery();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
            } else bExit = true;
        }
    }//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
    
    /**
     * Esta funcion permite cargar un fichero .xml
     */
    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);
            
            Animation conf=(Animation) u.unmarshal(new FileInputStream(file));
            java.util.List locators=conf.getImageLocator();
            int size=locators.size();
            
            Image itemp[]=new Image[size];
            for (int k=0;k<size;k++) {
                itemp[k]=Toolkit.getDefaultToolkit().getImage(new URL("file:/"+sBase+sRuta+(String)locators.get(k)));
               
                trk.addImage(itemp[k],k);
            }
            
            trk.waitForAll();
            
            // Si todo se ha cargado correctamente, se inicializa todo lo dem�s
            hAnimated1.setAnimateContent(itemp, HState.ALL_STATES);
            
            images=new Vector();
            for (int k=0;k<locators.size();k++) {
                images.add(itemp[k]);
                
                Object temp[]=new Object[1];
                temp[0]=locators.get(k);
                tableModel.addRow(temp);
            }
            
            updateGallery();
            
            if (tableModel.getRowCount()==0) return;
            
            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(0, 0);
            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * El usuario ha pulsado sobre el bot�n 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).
        // Ademas hay que copiar las imagenes al mismo directorio
        try {
            setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            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>();
            
            Animation conf=objFactory.createAnimation();
            java.util.List locators=conf.getImageLocator();
            
            for (int i=0;i<tableModel.getRowCount();i++) {
                String sImage = (String) tableModel.getValueAt(i,0);
                locators.add(sImage);
                //Copiamos las imagenes
                java.io.File oComponentFile = new java.io.File(oDirComponent,sImage);
                oFiles.add(oComponentFile);
                if (!oComponentFile.exists()) {
                    MainFrame.copyFile(new java.io.File(sBase+sRuta+sImage), oComponentFile);
                    }
            }
            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            oFiles.add(oFile);
            m.marshal(conf, new FileOutputStream(oFile));
            MainFrame.oMainFrame.getEditionProperty().putOptionFiles(oFiles, MainFrame.oMainFrame.getPSheet().getSelectedOption());
            oDialog.setAction(ContentEditorDialog.OK,sDir+sFile);
        } catch (Exception ex) {
            ex.printStackTrace();
            oDialog.setAction(ContentEditorDialog.CANCEL,null); // Si se produce alg�n error es como cancelar el proceso
            
        }
        setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
        oDialog.dispose();
        
        
    }//GEN-LAST:event_jButton10ActionPerformed
    
    private void jTable1MouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jTable1MouseClicked
    {//GEN-HEADEREND:event_jTable1MouseClicked
        // Cuando se selecciona una fila de la tabla hay que mostrar las im�genes asociadas
        int fil=jTable1.getSelectedRow();
        if (fil==-1) return;
        java.awt.Component oComp = jPanel3.getComponent(fil);
        jScrollPane3.getViewport().setViewPosition(oComp.getLocation());
        jScrollPane3.validate();
        
    }//GEN-LAST:event_jTable1MouseClicked
    
    private void updateGallery() {
        jPanel3.setVisible(false);
        jPanel3.removeAll();
        for (int i=0;i<images.size();i++) {
            HImage himg=new HImage();
            himg.setImage((Image) images.get(i));
            Image temp=(Image) images.get(i);
            jPanel3.add(himg);
        }
        
        jPanel3.setVisible(true);
    }
    
    public Dimension getPreferredSize() {
        return new Dimension(600,400);
    }
    
    
    /**
     * Devuelve los ficheros anadidos
     */
    public java.util.ArrayList<java.io.File> getFiles() {
        return oAddedFiles;
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.uvigo.mhp.ui.HAnimated hAnimated1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton12;
    private javax.swing.JButton jButton15;
    private javax.swing.JButton jButton16;
    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 jPanel14;
    private javax.swing.JPanel jPanel17;
    private javax.swing.JPanel jPanel18;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel20;
    private javax.swing.JPanel jPanel21;
    private javax.swing.JPanel jPanel22;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}