package uk.ac.reload.editor.style;

//M: style preferences editor dialog
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import org.jdom.Element;
import uk.ac.reload.editor.contentpackaging.editor.manifestview.ManifestTree;
import uk.ac.reload.editor.contentpackaging.editor.resourceview.CP_ResourcesPanel;
import uk.ac.reload.editor.contentpackaging.xml.ContentPackage;

public class StylePreferences_EditorDialog extends javax.swing.JDialog {

    PreferencesTableModel oTableModel;
    PreferencesCellRenderer oPreferencesCellRenderer;
    PreferencesCellEditor oPreferencesCellEditor;
    ContentPackage contentpackage;
    private static StylePreferences_EditorDialog instance;
    private java.util.ArrayList<Value> valuesBefore;
    Element styleelement;
  
    public StylePreferences_EditorDialog(java.awt.Frame parent, ContentPackage contentpackage, Element styleelement,java.util.ArrayList<Value> values) {
        super(parent, true);

        this.addWindowListener(new java.awt.event.WindowAdapter() {

            public void windowClosing(java.awt.event.WindowEvent oEvento) {
                cancel();
                JDialogClosing();
            }
        });
        instance = this;
        this.contentpackage = contentpackage;
        this.styleelement = styleelement;

       oTableModel = new PreferencesTableModel(values);
        oTableModel.addTableModelListener(oTableModel);

        //guardamos los valores al inicio (por si cancel o x) -copia, que sino se modifican
        valuesBefore = oTableModel.getCloneValues();

        initComponents();

        oPreferencesCellRenderer = new PreferencesCellRenderer();
        oPreferencesCellEditor = new PreferencesCellEditor();

        //El table model también escucha las selecciones en la tabla
        table.getSelectionModel().addListSelectionListener(oTableModel);

        table.setModel(oTableModel);

        table.getColumnModel().getColumn(0).setMinWidth(150);
        table.getColumnModel().getColumn(0).setMaxWidth(150);
        table.getColumnModel().getColumn(1).setMinWidth(150);
        table.getColumnModel().getColumn(1).setMaxWidth(150);

        DefaultTableCellRenderer dhr = (DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer();
        dhr.setHorizontalAlignment(SwingConstants.CENTER);
        DefaultTableCellRenderer dc0r = (DefaultTableCellRenderer) table.getDefaultRenderer(table.getColumnClass(0));
        dc0r.setForeground(java.awt.Color.BLUE);

        //Establecemos renderer y editor de la columna value (la name tendrá el renderer por defecto)
        table.getColumnModel().getColumn(1).setCellRenderer(oPreferencesCellRenderer);
        table.getColumnModel().getColumn(1).setCellEditor(oPreferencesCellEditor);

        table.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        okButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Edit Style Preferences");
        setBounds(new java.awt.Rectangle(400, 300, 300, 300));
        setIconImage(new javax.swing.ImageIcon(getClass().getResource("/uk/ac/reload/editor/resources/images/editstyle.gif")).getImage());

        okButton.setText("   OK   ");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        table.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)));
        table.setModel(oTableModel);
        table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        table.setAutoscrolls(false);
        table.setRowHeight(20);
        table.setVerifyInputWhenFocusTarget(false);
        jScrollPane1.setViewportView(table);

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(49, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(129, Short.MAX_VALUE)
                .addComponent(cancelButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(okButton)
                .addGap(135, 135, 135))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap(40, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        try {
            // Cambiamos los recursos anteriores (imágenes y música) del cp por los editados
            java.util.ArrayList<Value> valuesAfter = oTableModel.getValues();
            if (!valuesAfter.equals(valuesBefore)) {
                //.. siempre y cuando se hayan hecho modificaciones
                for (int i = 0; i < 11; i++) {
                    if ((i > 4) && (i < 9)) continue; //saltamos los font y font color
                    File fBefore = (File) valuesBefore.get(i).getValue();
                    File fAfter = (File) valuesAfter.get(i).getValue();

                    if (!fAfter.equals(fBefore)) fBefore.delete(); //nos quedamos sólo con el nuevo (teníamos los dos en cp)
                }
                //Hacemos refresh del arbol de recursos
                CP_ResourcesPanel.getInstance().refreshResourceTree();
            }

            //Actualizamos stylevalues en ManifestTree (para futuras ediciones)
            ManifestTree.getInstance().setStyleValues(valuesAfter);

            
            List previousElements = styleelement.getChildren();//GEN-LAST:event_okButtonActionPerformed
            int i = 0;
            for (Iterator it = previousElements.iterator(); it.hasNext();) {
                Element e = (Element) it.next();
                if (e.getName().contains("font")) {
                    List fontchild = e.getChildren();
                    ((Element) (fontchild.get(0))).setText(((java.awt.Font) (valuesAfter.get(i).getValue())).getFontName());
                    ((Element) (fontchild.get(1))).setText(new Integer(((java.awt.Font) (valuesAfter.get(i).getValue())).getStyle()).toString());
                    ((Element) (fontchild.get(2))).setText(new Integer(((java.awt.Font) (valuesAfter.get(i).getValue())).getSize()).toString());
                } else if (e.getName().contains("color")) {
                    List colorchild = e.getChildren();
                    ((Element) (colorchild.get(0))).setText(new Integer(((java.awt.Color) (valuesAfter.get(i).getValue())).getRed()).toString());
                    ((Element) (colorchild.get(1))).setText(new Integer(((java.awt.Color) (valuesAfter.get(i).getValue())).getGreen()).toString());
                    ((Element) (colorchild.get(2))).setText(new Integer(((java.awt.Color) (valuesAfter.get(i).getValue())).getBlue()).toString());
                } else {
                    e.setText(((File) (valuesAfter.get(i).getValue())).getName());
                }
                i++;
            }
            contentpackage.saveDocument();

            JDialogClosing();
        } catch (IOException ex) {
            System.out.println(ex);
        }
}                                        

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        cancel();
        JDialogClosing();
}//GEN-LAST:event_cancelButtonActionPerformed

    private void cancel() {
        // Borramos los recursos editados
        java.util.ArrayList<Value> valuesAfter = oTableModel.getValues();
        if (!valuesAfter.equals(valuesBefore)) { //.. siempre y cuando se hayan hecho modificaciones
            for (int i = 0; i < 11; i++) {
                if ((i > 4) && (i < 9)) continue; //saltamos los font y font color
                File fBefore = (File) valuesBefore.get(i).getValue();
                File fAfter = (File) valuesAfter.get(i).getValue();
                if (!fAfter.equals(fBefore)) fAfter.delete(); //borramos el nuevo
            }
            //Hacemos refresh del arbol de recursos
            CP_ResourcesPanel.getInstance().refreshResourceTree();// no haría falta (queda igual)
        }
    }

    /**
     * Esta función es llamada cuando el usuario pulse la aspa
     * de cerrar la ventana.
     */
    public void JDialogClosing() {
        this.setVisible(false);
    }

    public static StylePreferences_EditorDialog getInstance() {
        return instance;
    }

    public File getActualProjectFolder() {
        return contentpackage.getProjectFolder();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton okButton;
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables
}
