/*
 * MetadataForm.java
 *
 */

package com.uvigo.tMaestro.SCOCreator.tool.metadata;

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

/**
 * Esta clase es un dialogo que muestra al usuario un formulario para cubrir
 * los datos (metadatos) sobre el objeto educativo. La funcion
 * guarda los datos en una estructura alojada en MainFrame. El formulario es una formulario
 * dinamico, en el sentido, que sus campos se cargan de un fichero de configuracion (.xml)
 * De esta forma pueden anadirse nuevos elementos a la descripcion del SCO mediante metadatos.
 * Ademas, tambien se indica el tipo de cada unos de los metadatos y los valores que
 * puede tomar cada uno de ellos. De la carga del fichero .xml de encarga la clase FormManager
 * @author  raul
 * @version 0.1
 */
public class MetadataForm extends javax.swing.JDialog {
    
    final private static java.awt.Color oColor = new java.awt.Color(90,90,243);
    final private static java.awt.Color oColorPanel = new java.awt.Color(113,157,201);
    
    /**
     * Constructor de la clase.
     */
    public MetadataForm(java.awt.Frame parent) {
        super(parent, true);
        initComponents();
        makeForm();
    }
    
    
    /**
     * Este metodo a partir de las estructuras de vocabulario (y sus Levels) del FormManager
     * construye dinamicamente el formulario (los formularios) que se va a presentar al
     * usuario
     */
    private void makeForm() {
        MetadataManager oMetadataManager = MainFrame.oMainFrame.getMetadataManager();
        for (int z=0;z<oMetadataManager.getVocabularyCount();z++) {
            
            javax.swing.JScrollPane oJScrollPane1 = new javax.swing.JScrollPane();
            javax.swing.JPanel oJPanel1 = new javax.swing.JPanel();
            oJPanel1.setLayout(new java.awt.GridBagLayout());
            oJScrollPane1.setViewportView(oJPanel1);
            
            java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            gridBagConstraints.weightx = 1.0;
            gridBagConstraints.weighty = 0.9;
            gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
            getContentPane().add(oJScrollPane1, gridBagConstraints);
            
            oJTabbedPane1.add(oMetadataManager.getVocabularyName(z),oJScrollPane1);
            
            java.awt.Insets oInsets = new java.awt.Insets(5,5,5,5);
            for(int i=0;i<oMetadataManager.getLevelCount(z);i++) {
                Level oLevel = MainFrame.oMainFrame.getMetadataManager().getLevel(z,i);
                //Panel que contiene los elementos de la categoria
                final javax.swing.JPanel oPanel = new javax.swing.JPanel();
                final javax.swing.JLabel oLabel = new javax.swing.JLabel("+"+oLevel.getScreenName());
                oLabel.setForeground(oColor);
                oLabel.setVisible(true);
                oPanel.setLayout(new java.awt.GridBagLayout());
                oPanel.setVisible(false);
                javax.swing.border.TitledBorder oBorder = javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(oColor ,2),oLevel.getScreenName(),javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,javax.swing.border.TitledBorder.DEFAULT_POSITION);
                oBorder.setTitleColor(oColor);
                oPanel.setBorder(oBorder);
                oPanel.addMouseListener(new java.awt.event.MouseAdapter() {
                    public void mouseClicked(java.awt.event.MouseEvent oE) {
                        clickedPanel(oE,oPanel,oLabel);
                    }
                    
                });
                oLabel.addMouseListener(new java.awt.event.MouseAdapter() {
                    public void mouseClicked(java.awt.event.MouseEvent oE) {
                        clickedLabel(oE,oPanel,oLabel);
                    }
                    
                });
                for (int y=0;y<oLevel.sizeElements();y++) {
                    Element oElement = oLevel.getElement(y);
                    insertElement(z,oPanel,oElement);
                }
                
                //Anadimos el panel con los elementos de la categoria al formulario
                gridBagConstraints = new java.awt.GridBagConstraints();
                gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
                gridBagConstraints.weightx = 1.0;
                gridBagConstraints.weighty = 1.0;
                gridBagConstraints.gridx=java.awt.GridBagConstraints.RELATIVE;
                gridBagConstraints.gridwidth=java.awt.GridBagConstraints.REMAINDER;
                gridBagConstraints.insets=oInsets;
                oJPanel1.add(oPanel,gridBagConstraints);
                oJPanel1.add(oLabel,gridBagConstraints);
            }
        }
    }
    
    
    private void insertElement(int z,javax.swing.JPanel oPanel,Element oElement) {
        java.awt.Insets oInsets=new java.awt.Insets(5,5,5,5);
        java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
        if (oElement.getType()==Element.COMPLEX) {
            //Panel que contiene los elementos hijos
            javax.swing.JPanel oPanelHijo = new javax.swing.JPanel();
            oPanelHijo.setLayout(new java.awt.GridBagLayout());
            javax.swing.border.TitledBorder oBorder = javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(oColorPanel,2),oElement.getScreenName(),javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,javax.swing.border.TitledBorder.DEFAULT_POSITION);
            oBorder.setTitleColor(oColorPanel);
            oPanelHijo.setBorder(oBorder);
            for(int i=0;i<oElement.sizeElements();i++) {
                Element oHijo = oElement.getElement(i);
                insertElement(z,oPanelHijo,oHijo);
            }
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
            gridBagConstraints.weightx = 1.0;
            gridBagConstraints.weighty = 1.0;
            gridBagConstraints.gridx=java.awt.GridBagConstraints.RELATIVE;
            gridBagConstraints.gridwidth=java.awt.GridBagConstraints.REMAINDER;
            gridBagConstraints.insets=oInsets;
            oPanel.add(oPanelHijo,gridBagConstraints);
        } else {
            gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
            gridBagConstraints.weightx = 0.01;
            gridBagConstraints.weighty = 1.0;
            gridBagConstraints.gridx=java.awt.GridBagConstraints.RELATIVE;
            //gridBagConstraints.gridwidth=java.awt.GridBagConstraints.RELATIVE;
            gridBagConstraints.insets=oInsets;
            javax.swing.JLabel oLabelElement = new javax.swing.JLabel(oElement.getScreenName());
            oPanel.add(oLabelElement,gridBagConstraints);
            java.awt.Component oComponent = oElement.getComponent(z);
            gridBagConstraints.weightx = 0.99;
            gridBagConstraints.gridx=java.awt.GridBagConstraints.RELATIVE;
            if (!oElement.getName().contains("---")) gridBagConstraints.gridwidth=java.awt.GridBagConstraints.REMAINDER;
            //else gridBagConstraints.gridwidth=java.awt.GridBagConstraints.RELATIVE;
            oPanel.add(oComponent,gridBagConstraints);
        }
        
    }
    
    
    /** 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() {
        java.awt.GridBagConstraints gridBagConstraints;

        oJButton1 = new javax.swing.JButton();
        oJButton1.setText(MainFrame.oMainFrame.getMessage("Button2"));
        oJTabbedPane1 = new javax.swing.JTabbedPane();

        getContentPane().setLayout(new java.awt.GridBagLayout());

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        oJButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                oJButton1ActionPerformed(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 0.1;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
        getContentPane().add(oJButton1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 0.9;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(oJTabbedPane1, gridBagConstraints);

        setSize(new java.awt.Dimension(680, 480));
    }// </editor-fold>//GEN-END:initComponents
    
    /**
     * LLamado cuando el usuario pulsa sobre el panel
     */
    private void clickedPanel(java.awt.event.MouseEvent oE, javax.swing.JPanel oPanel,javax.swing.JLabel oLabel) {
        if (oE.getPoint().getY()<15) {
            oPanel.setVisible(false);
            oLabel.setVisible(true);
        }
    }
    
    /**
     * LLamado cuando el usuario pulsa sobre la etiqueta
     */
    private void clickedLabel(java.awt.event.MouseEvent oE, javax.swing.JPanel oPanel,javax.swing.JLabel oLabel) {
        oLabel.setVisible(false);
        oPanel.setVisible(true);
    }
    
    
    /**
     * Metodo llamado cuando el usuario pulsa el boton de cerrar
     * Salvamos todos los valores de los metadatos a la estructura de
     * metadatos del MainFrame
     */
    private void oJButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_oJButton1ActionPerformed
        for (int y=0;y<MainFrame.oMainFrame.getMetadataManager().getVocabularyCount();y++) {
            MainFrame.oMainFrame.removeMetadataGroup(y);
            java.util.HashMap<String,Object> oMetadataGroup= new java.util.HashMap<String,Object>();
            for (int i=0;i<MainFrame.oMainFrame.getMetadataManager().getLevelCount(y);i++) {
                Level oLevel = MainFrame.oMainFrame.getMetadataManager().getLevel(y,i);
                for (int z=0;z<oLevel.sizeElements();z++) {
                    saveElement(oMetadataGroup,oLevel.getElement(z));
                }
            }
            if (oMetadataGroup.size()!=0) MainFrame.oMainFrame.addMetadataGroup(oMetadataGroup);
        }
        this.setVisible(false);
    }//GEN-LAST:event_oJButton1ActionPerformed
    
    
    /**
     * Metodo que guarda el valor del elemento del formulario de metadatos en
     * la estructura de metadatos oMetadataGroup
     */
    private void saveElement(java.util.HashMap<String,Object> oMetadataGroup,Element oElement) {
        if (oElement.getType()==Element.COMPLEX) {
            for (int i=0;i<oElement.sizeElements();i++) saveElement(oMetadataGroup,oElement.getElement(i));
        } else {
            
            if (oElement.getValue()!=null) {
                oMetadataGroup.put(oElement.getPrefixName()+"."+oElement.getName(),oElement.getValue());
                //System.out.println(oElement.getPrefixName()+"."+oElement.getName()+" --> "+oElement.getValue().toString());
            }
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton oJButton1;
    private javax.swing.JTabbedPane oJTabbedPane1;
    // End of variables declaration//GEN-END:variables
    
}
