package com.uvigo.mhp.xml;

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.activeImage.*;

public class ActiveImageContentEditorPanel extends JPanel
{
    private DefaultTableModel tableModel;
    
    private JAXBContext jc;
    private ObjectFactory objFactory;
    private ActiveImageConfiguration conf;
    private java.util.List zones;
    
    private MediaTracker trk;
    
    public ActiveImageContentEditorPanel()
    {
        initComponents();
        try
        {
            jc=JAXBContext.newInstance("com.uvigo.mhp.xml.activeImage");
            objFactory = new ObjectFactory();
            conf=objFactory.createActiveImageConfiguration();
            zones=conf.getActiveZone();
        }
        catch (JAXBException ex)
        {
            System.out.println(ex.getMessage());
        }
        
        tableModel=(DefaultTableModel) jTable1.getModel();
        trk=new MediaTracker(this);
        jScrollPane2.getViewport().setBackground(Color.white);
        jScrollPane2.getViewport().setOpaque(true);
    }
    
    private void initComponents()//GEN-BEGIN:initComponents
    {
        jPanel13 = new javax.swing.JPanel();
        jButton12 = new javax.swing.JButton();
        jButton11 = new javax.swing.JButton();
        jButton10 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        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();
        jTextField3 = new javax.swing.JTextField();
        jButton15 = new javax.swing.JButton();

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

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

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

        jPanel13.add(jButton12);

        jButton11.setText("Cargar");
        jButton11.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton11ActionPerformed(evt);
            }
        });

        jPanel13.add(jButton11);

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

        jPanel13.add(jButton10);

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

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

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

        jPanel20.setBorder(new javax.swing.border.TitledBorder("Zonas activas "));
        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.setBackground(new java.awt.Color(255, 255, 255));
        jScrollPane2.setAutoscrolls(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][]
            {

            },
            new String []
            {
                "Localizador", "Contexto", "Texto"
            }
        )
        {
            Class[] types = new Class []
            {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex)
            {
                return types [columnIndex];
            }
        });
        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);

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

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

        jPanel22.setBorder(new javax.swing.border.TitledBorder("Imagen principal"));
        jTextField3.setBackground(new java.awt.Color(255, 255, 255));
        jTextField3.setColumns(20);
        jPanel22.add(jTextField3, java.awt.BorderLayout.CENTER);

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

        jPanel22.add(jButton15, java.awt.BorderLayout.EAST);

        jPanel3.add(jPanel22, java.awt.BorderLayout.SOUTH);

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

    }//GEN-END:initComponents
        
    private void jButton15ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton15ActionPerformed
    {//GEN-HEADEREND:event_jButton15ActionPerformed
        // Configurar la imagen principal
        
        javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
        int option = chooser.showOpenDialog(this);
        if (option == javax.swing.JFileChooser.APPROVE_OPTION)
        {
            try
            {
                File file = chooser.getSelectedFile();
                if (file == null) return;
                
                URL url=file.toURL();
                Image temp=Toolkit.getDefaultToolkit().getImage(url);
                trk.addImage(temp,0);
                trk.waitForAll();
                
                conf.setBackgroundImage(url.toString());
                jTextField3.setText(url.toString());
                jTextField3.setCaretPosition(0);
            }
            catch (Exception ex)
            {
                System.out.println(ex);
            }
        }
    }//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);
        Object ob1=zones.get(i);
        Object ob2=zones.get(i-1);
        zones.set(i, ob2);
        zones.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=zones.get(i);
        Object ob2=zones.get(i+1);
        zones.set(i, ob2);
        zones.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 la fila actual
        int i=jTable1.getSelectedRow();
        if (i==-1) return;
        
        tableModel.removeRow(i);
        zones.remove(i);
        
        if (jTable1.getRowCount()>0)
        {
            jTable1.setColumnSelectionInterval(0, 0);
            if (i==jTable1.getRowCount())
                jTable1.setRowSelectionInterval(i-1, i-1);
            else
                jTable1.setRowSelectionInterval(i, i);
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    
    private void jButton17ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton17ActionPerformed
    {//GEN-HEADEREND:event_jButton17ActionPerformed
        // Insertar una fila
        try
        {
            Object temp[]=new Object[3];
            temp[0]=new String("");
            temp[1]=new String("");
            temp[2]=new String("");
            tableModel.addRow(temp);
            
            ActiveZoneType azt=objFactory.createActiveZoneType();
            azt.setLocator("");
            azt.setContextName("");
            azt.setComment("");
            
            zones.add(azt);
            
            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(jTable1.getRowCount()-1, jTable1.getRowCount()-1);
        }
        catch (Exception ex)
        {}
    }//GEN-LAST:event_jButton17ActionPerformed
    
    private void jButton12ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton12ActionPerformed
    {//GEN-HEADEREND:event_jButton12ActionPerformed
        // Hay que reinicializar todos los componentes
        try
        {
            conf=objFactory.createActiveImageConfiguration();
            zones=conf.getActiveZone();
            int i=tableModel.getRowCount();
            for (int j=0;j<i;j++)
                tableModel.removeRow(0);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jButton12ActionPerformed
    
    private void jButton11ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton11ActionPerformed
    {//GEN-HEADEREND:event_jButton11ActionPerformed
        // Hay que cargar el contenido de un fichero XML.
        
        javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
        int option = chooser.showOpenDialog(this);
        if (option == javax.swing.JFileChooser.APPROVE_OPTION)
        {
            try
            {
                File file = chooser.getSelectedFile();
                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);
                conf=(ActiveImageConfiguration) u.unmarshal(new FileInputStream(file));
                
                jTextField3.setText(conf.getBackgroundImage());
                
                zones=conf.getActiveZone();
                
                for (int k=0;k<zones.size();k++)
                {
                    Object temp[]=new Object[3];
                    temp[0]=((ActiveZoneType) zones.get(k)).getLocator();
                    temp[1]=((ActiveZoneType) zones.get(k)).getContextName();
                    temp[2]=((ActiveZoneType) zones.get(k)).getComment();
 
                    tableModel.addRow(temp);
                }
                
                if (tableModel.getRowCount()==0) return;
                
                jTable1.setColumnSelectionInterval(0, 0);
                jTable1.setRowSelectionInterval(0, 0);
                select(0);
            }
            catch (Exception ex)
            {
                System.out.println(ex);
            }
        }
    }//GEN-LAST:event_jButton11ActionPerformed
    
    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.
        // Hay que actualizar los campos de texto a los valores indicados en la tabla.
        
        if (jTextField3.getText().equals("")) return;
        
        javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
        int option = chooser.showSaveDialog(this);
        
        if (option == javax.swing.JFileChooser.APPROVE_OPTION)
        {
            try
            {
                File file = chooser.getSelectedFile();
                if (file == null) return;
                
                for (int i=0;i<tableModel.getRowCount();i++)
                {
                    ActiveZoneType azt=(ActiveZoneType) zones.get(i);
                    azt.setLocator((String) tableModel.getValueAt(i,0));
                    azt.setContextName((String) tableModel.getValueAt(i,1));
                    azt.setComment((String) tableModel.getValueAt(i,2));
                }
    
                conf.setBackgroundImage(jTextField3.getText());
                Marshaller m = jc.createMarshaller();
                m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                m.marshal(conf, new FileOutputStream(file));
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                System.out.println(ex);
            }
        }
    }//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 imagenes asociadas
        Point p=new Point(evt.getX(),evt.getY());
        int fil=jTable1.rowAtPoint(p);
        if (fil==-1) return;
        select(fil);
    }//GEN-LAST:event_jTable1MouseClicked
    
    private void select(int fil)
    {
/*        MenuElementType met=(MenuElementType) zones.get(fil);
        try
        {
            if ((met.getSelectedImage()!=null) && (!(met.getSelectedImage().equals(""))))
            {
                URL url=new URL(met.getSelectedImage());
                Image img=Toolkit.getDefaultToolkit().getImage(url);
                trk.addImage(img,0);
                trk.waitForAll();
 
                if ((img!=null) && (img.getWidth(null)!=-1) && (img.getHeight(null)!=-1))
                {
                    jLabel2.setIcon(new ImageIcon(img));
                    jTextField2.setText(url.toString());
                    jTextField2.setCaretPosition(0);
                }
            }
            else
            {
                jLabel2.setIcon(null);
                jTextField2.setText("");
                jTextField2.setCaretPosition(0);
            }
        }
        catch (Exception ex)
        {}
 
        try
        {
            if ((met.getNotSelectedImage()!=null) && (!(met.getNotSelectedImage().equals(""))))
            {
                URL url=new URL(met.getNotSelectedImage());
                Image img=Toolkit.getDefaultToolkit().getImage(url);
                trk.addImage(img,0);
                trk.waitForAll();
 
                if ((img!=null) && (img.getWidth(null)!=-1) && (img.getHeight(null)!=-1))
                {
                    jLabel3.setIcon(new ImageIcon(img));
                    jTextField3.setText(url.toString());
                    jTextField3.setCaretPosition(0);
                }
            }
            else
            {
                jLabel3.setIcon(null);
                jTextField3.setText("");
                jTextField3.setCaretPosition(0);
            }
        }
        catch (Exception ex)
        {}*/
    }
    
    public Dimension getPreferredSize()
    {
        return new Dimension(600,400);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton12;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JButton jButton11;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jButton10;
    private javax.swing.JPanel jPanel22;
    private javax.swing.JPanel jPanel21;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jButton15;
    private javax.swing.JButton jButton17;
    private javax.swing.JPanel jPanel20;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}