/* Copyright Nabil Alikhan. 2010.
 * This file is part of BLAST Ring Image Generator (BRIG).
 * BRIG is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * BRIG is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with BRIG.  If not, see <http://www.gnu.org/licenses/>.
 */


package brig;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import org.jdom.*;
import org.jdom.input.SAXBuilder;

/**
 *
 * @author nabil
 */
public class QuickProfile extends javax.swing.JFrame {

    /** Creates new form QuickProfile */
    public QuickProfile() {
        initComponents();
        File prof = new File("profiles");
        if(!prof.exists()){
            prof.mkdir();
        }
        File[] list = prof.listFiles();
        for(int i=0;i<list.length;i++){
           if(!list[i].isHidden() && list[i].isFile() && !list[i].toString().endsWith(".jpg")){
                norings.addItem(list[i].getName());
            }
        }
    }

    /** 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        norings = new javax.swing.JComboBox();
        jLabel75 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel87 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Load a template");

        norings.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                noringsItemStateChanged(evt);
            }
        });

        jLabel75.setText("Preset profile:");

        jButton2.setText("Save & close");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel87.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel87.setText("jLabel87");

        jButton1.setText("Close");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel75)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 145, Short.MAX_VALUE)
                .add(norings, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 185, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(jButton2)
                .add(18, 18, 18)
                .add(jButton1)
                .add(55, 55, 55))
            .add(layout.createSequentialGroup()
                .add(38, 38, 38)
                .add(jLabel87, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 488, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(125, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(norings, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton2)
                    .add(jLabel75)
                    .add(jButton1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel87, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 359, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void noringsItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_noringsItemStateChanged
        try {
            File doop = new File("profiles" + BRIG.SL + norings.getSelectedItem().toString() + ".jpg");
            Image img = ImageIO.read( doop );
            Image newimg = img.getScaledInstance(400, 400,  java.awt.Image.SCALE_SMOOTH);
            ImageIcon icon = new ImageIcon(newimg);
            jLabel87.setIcon(icon);
            jLabel87.setText("");
        } catch (IIOException e) {
            jLabel87.setIcon(null);
            jLabel87.setText("No preview image could be found.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_noringsItemStateChanged

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        String fi = "profiles"+BRIG.SL + norings.getSelectedItem().toString();
        File get = new File(fi);
        if (get.exists()) {
            try {
                SAXBuilder builder = new SAXBuilder();
                try {
                    Document temp =  builder.build(get.getPath());
                    if(temp.getRootElement().getAttributeValue("legendPosition") != null ){
                        System.out.print( temp.getRootElement().getAttributeValue("legendPosition")   );
                        BRIG.PROFILE.getRootElement().setAttribute("legendPosition",  temp.getRootElement().getAttributeValue("legendPosition") );
                        if(temp.getRootElement().getChild("cgview_settings") != null ){
                            BRIG.PROFILE.getRootElement().removeChild("cgview_settings");
                            Element cop = temp.getRootElement().getChild("cgview_settings");
                            cop.detach();
                            BRIG.PROFILE.getRootElement().addContent(cop);
                            this.dispose();
                        }else{
                    JOptionPane.showMessageDialog(this,
                            get.getName() + " uses an out of date format",
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                    }
                    }else{
                    JOptionPane.showMessageDialog(this,
                            get.getName() + " uses an out of date format",
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                    }
                } catch (JDOMException e) {
                    JOptionPane.showMessageDialog(this,
                            get.getName() + " is corrupt because :\n" + e.getMessage(),
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(this,
                            "Could not read " + get.getName() + " because :\n" + e.getMessage(),
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this,
                        "This is not a valid save file " + e.getMessage(),
                        "ERROR!",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new QuickProfile().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel75;
    private javax.swing.JLabel jLabel87;
    private javax.swing.JComboBox norings;
    // End of variables declaration//GEN-END:variables

}
