/*
 * ChooseTemplate.java
 */
package com.uvigo.tMaestro.SCOCreator.tool;

/**
 * Esta clase constituye el cuadro de di�logo que permite seleccionar
 * entre las plantillas que se acompa�an junto con la herramienta.
 * Proporciona una vista previa de las plantillas.
 * @author  raul
 * @version 0.1
 */
public class ChooseTemplate extends javax.swing.JDialog {

    /**
     * Referencia al MainFrame de la herramienta
     */
    private MainFrame oMainFrame;
    /**
     * PLantilla elegida para cargar
     */
    private String sTemplate = null;

    /**
     * Crea una nueva instancia del cuadro de dialogos
     * @param oParent El padre de este di�logo, ser� el MainFrame
     * @throws Exception Si hay alg�n problema al localizar o procesar las plantillas
     */
    public ChooseTemplate(java.awt.Frame oParent) throws Exception {
        super(oParent, true);
        //System.out.println("CHOOSE TEMPLATE");
        oMainFrame = (MainFrame) oParent;
        initComponents();
        oJPanel11.setBorder(new javax.swing.border.TitledBorder(oMainFrame.getMessage("Border1")));
        oJButton1.setText(oMainFrame.getMessage("Button5"));
        oJButton2.setText(oMainFrame.getMessage("Button6"));
        oJLabel2.setText(oMainFrame.getMessage("Label3"));

        //M: Vemos qu� plantillas tenemos almacenadas en la aplicaci�n (directorio TEMPLATES en user.dir)
        java.util.ArrayList<String> oTemplates = new java.util.ArrayList<String>();
        java.io.File[] oFiles = oMainFrame.fTemplates.listFiles();
        int j = 0;
        for (j = 0; j < oFiles.length; j++) {
            oTemplates.add(oFiles[j].getName());
       }

        int i = 0;
        javax.swing.DefaultListModel oModel = new javax.swing.DefaultListModel();
        for (i = 0; i < oTemplates.size(); i++) { //A�adimos al JList cada una de las plantillas
           oModel.addElement(oTemplates.get(i));
        }
        oJList1.setModel(oModel);
        oJList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {

            public void valueChanged(javax.swing.event.ListSelectionEvent oE) {
                userSelection(oE);
            }
        });
    }

    /** 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;

        oJPanel3 = new javax.swing.JPanel();
        oJLabel2 = new javax.swing.JLabel();
        oJTextField1 = new javax.swing.JTextField();
        oJPanel1 = new javax.swing.JPanel();
        oJScrollPane1 = new javax.swing.JScrollPane();
        oJList1 = new javax.swing.JList();
        oJPanel11 = new javax.swing.JPanel();
        oJLabel1 = new javax.swing.JLabel();
        oJPanel2 = new javax.swing.JPanel();
        oJButton1 = new javax.swing.JButton();
        oJButton2 = new javax.swing.JButton();
        oJScrollPane2 = new javax.swing.JScrollPane();
        oJTextArea1 = new javax.swing.JTextArea();

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

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

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 2);
        oJPanel3.add(oJLabel2, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 10);
        oJPanel3.add(oJTextField1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 2.0;
        gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 0);
        getContentPane().add(oJPanel3, gridBagConstraints);

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

        oJList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        oJScrollPane1.setViewportView(oJList1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 2);
        oJPanel1.add(oJScrollPane1, gridBagConstraints);

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

        oJLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        oJLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        oJLabel1.setMaximumSize(new java.awt.Dimension(200, 200));
        oJLabel1.setMinimumSize(new java.awt.Dimension(200, 200));
        oJLabel1.setPreferredSize(new java.awt.Dimension(200, 200));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        oJPanel11.add(oJLabel1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 2.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 10);
        oJPanel1.add(oJPanel11, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 2.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
        getContentPane().add(oJPanel1, gridBagConstraints);

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

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

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
        oJPanel2.add(oJButton1, gridBagConstraints);

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

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
        oJPanel2.add(oJButton2, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
        getContentPane().add(oJPanel2, gridBagConstraints);

        oJScrollPane2.setMinimumSize(new java.awt.Dimension(440, 55));
        oJScrollPane2.setPreferredSize(new java.awt.Dimension(440, 55));
        oJTextArea1.setEditable(false);
        oJTextArea1.setLineWrap(true);
        oJTextArea1.setWrapStyleWord(true);
        oJTextArea1.setAutoscrolls(false);
        oJScrollPane2.setViewportView(oJTextArea1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 10);
        getContentPane().add(oJScrollPane2, gridBagConstraints);

        setSize(new java.awt.Dimension(472, 424));
    }
    // </editor-fold>//GEN-END:initComponents
    //Si el usuario pulsa el bot�n cancelar
    private void oJButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_oJButton2ActionPerformed
        sTemplate = null;
        this.setVisible(false);
    }//GEN-LAST:event_oJButton2ActionPerformed

    //Cuando el usuario pulsa sobre el boton OK
    private void oJButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_oJButton1ActionPerformed
        sTemplate = (String) oJList1.getSelectedValue();
        if (sTemplate == null) {
            java.awt.Toolkit.getDefaultToolkit().beep();
            MyOptionPane.showMessageDialog(this, oMainFrame.getMessage("Error14"), oMainFrame.getMessage("Title12"), javax.swing.JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (oJTextField1.getText().equals("")) {
            java.awt.Toolkit.getDefaultToolkit().beep();
            MyOptionPane.showMessageDialog(this, oMainFrame.getMessage("Error13"), oMainFrame.getMessage("Title12"), javax.swing.JOptionPane.ERROR_MESSAGE);
            return;
        }


        this.setVisible(false);
    }//GEN-LAST:event_oJButton1ActionPerformed

    /**
     * Esta funci�n es llamada cuando el usuario realiza alg�n evento
     * de selecci�n sobre la JList del di�logo. Detecta c�al es la plantilla
     * seleccionada por el usuario y muestra una previsualizaci�n de �sta
     * en el panel adyacente a la lista.
     */
    private void userSelection(javax.swing.event.ListSelectionEvent oE) {
       // System.out.println("userSelection");
        if (oE.getValueIsAdjusting() == false) {
            if (oJList1.getSelectedIndex() != -1) {
                try {
                    oJTextArea1.setText("");
                    oJLabel1.setIcon(null);
                    oJLabel1.setText(null);
                    String sTemplate = new String(((String) oJList1.getSelectedValue()));
                    //System.out.println(sTemplate);
                    java.net.URL oURL = getClass().getResource("/com/uvigo/tMaestro/SCOCreator/templates/" + sTemplate + ".jpeg");
                    javax.swing.ImageIcon oThumbnail = null;
                   // System.out.println(sTemplate+" "+oURL.getPath());
                    javax.swing.ImageIcon oTmpIcon = new javax.swing.ImageIcon(oURL);
                    if (oTmpIcon.getIconHeight() != oJLabel1.getHeight()) { // Escalamos la imagen utilizando un algortimo que priorice la carga de la imagen
                        oThumbnail = new javax.swing.ImageIcon(oTmpIcon.getImage().getScaledInstance(-1, oJLabel1.getHeight(), java.awt.Image.SCALE_FAST));
                    } else { //no hay necesidad de escalar la imagen
                        oThumbnail = oTmpIcon;
                    }

                    oJLabel1.setIcon(oThumbnail);

                    //Cargamos la descripci�n de la plantilla. 
                    java.net.URI oURI = (this.getClass().getResource("")).toURI();
                    java.io.InputStream oInput = this.getClass().getResource("/com/uvigo/tMaestro/SCOCreator/templates/" + sTemplate + ".txt").openStream();

                    if (oInput != null) { //Leemos la descripci�n de la plantilla y la mostramos al usuario
                        //Primero averiguamos el idioma en que ha arrancado la aplicaci�n
                        java.util.prefs.Preferences oPrefs = java.util.prefs.Preferences.userNodeForPackage(MainFrame.class);
                        String sLanCode = oPrefs.get("Code", java.util.Locale.getDefault().getLanguage());

                        java.io.BufferedReader oReader = new java.io.BufferedReader(new java.io.InputStreamReader(oInput));
                        oJTextArea1.setText("");
                        String sDescription = oReader.readLine();
                        while (sDescription != null) {
                            int iIndex = sDescription.indexOf("-");
                            if (iIndex != -1 && sDescription.substring(0, iIndex).equals(sLanCode)) {
                                oJTextArea1.setText(sDescription.substring(iIndex + 1));
                                break;
                            }
                            sDescription = oReader.readLine();
                        }
                        oReader.close();
                        oJTextArea1.setCaretPosition(0); //Para hacer que el Scroll se ponga al principio
                    }



                } catch (Exception oEx) {
                    oJLabel1.setText(oMainFrame.getMessage("Error7"));
                }
            }
        }
    }

    /**
     * Devuelve el nombre de la plantilla seleccionada
     * por el usuario.
     * @return Un String con el nombre de la clase sin extension
     */
    public String getTemplateName() {
        return sTemplate;
    }

    /**
     * Esta funci�n devuelve el nombre del proyecto introducido por el usuario.
     * @return El nombre del proyecto.
     */
    public String getProjectName() {
        return oJTextField1.getText();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton oJButton1;
    private javax.swing.JButton oJButton2;
    private javax.swing.JLabel oJLabel1;
    private javax.swing.JLabel oJLabel2;
    private javax.swing.JList oJList1;
    private javax.swing.JPanel oJPanel1;
    private javax.swing.JPanel oJPanel11;
    private javax.swing.JPanel oJPanel2;
    private javax.swing.JPanel oJPanel3;
    private javax.swing.JScrollPane oJScrollPane1;
    private javax.swing.JScrollPane oJScrollPane2;
    private javax.swing.JTextArea oJTextArea1;
    private javax.swing.JTextField oJTextField1;
    // End of variables declaration//GEN-END:variables
}
