/*
 * TablePreview.java
 *
 * Created on June 9, 2006, 8:20 AM
 */

package usda.weru.util.table.test;

import com.klg.jclass.table.TableDataModel;
import de.schlichtherle.truezip.file.TFile;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import usda.weru.util.table.WepsTableMeta;
import usda.weru.util.wepsFileChooser2.WepsFileChooser2;

/**
 *
 * @author  Joseph Levin
 */
public class TablePreview extends javax.swing.JFrame {
    private static final long serialVersionUID = 1L;
    
    private TFile c_xmlFile;
    
    public TablePreview(String path){
        initComponents();
        init();
        if (path != null && path.length() > 0){
            //A file was passed in
            c_xmlFile = new TFile(path);
            
            //Test it.
            if (!c_xmlFile.isFile()){
                //Failed the test(s)
                JOptionPane.showMessageDialog(this, "File not found.\n" + path, "Error", JOptionPane.WARNING_MESSAGE);
                c_xmlFile = null;
            }
        }
        //Prompt the user to select a file.
        if (c_xmlFile == null){
            WepsFileChooser2 jfc = new WepsFileChooser2("", WepsFileChooser2.Action.Open);
            jfc.setAcceptAllFileFilterUsed(true);
            jfc.setFileFilter(new XmlFileFilter());
            jfc.setMultiSelectionEnabled(false);
            jfc.setDialogTitle("Select Table File");
            jfc.setSelectedFile(c_xmlFile);
            while (c_xmlFile == null){
                if (jfc.showDialog(this) == WepsFileChooser2.APPROVE_OPTION){
                    TFile temp = new TFile(jfc.getSelectedFile());
                    if (temp.isFile()){
                        c_xmlFile = temp;
                        temp = null;
                    }
                } else{
                    mi_close.doClick();
                }
                
            }
        }
        
        //Call the example code.
        setupTable();
    }
    
    /**
     * Example WepsTable code.
     */
    protected void setupTable() {
        //Pass the table the file object for the xml definition.
        wepsTable.fromFile(c_xmlFile);
        
        //The meta object represents the xml file that has been loaded.
        //Only needed here so the datasource can build itself for testing.
        //Changing things directly in the meta is not tested.  Intended to be loaded from a file.
        WepsTableMeta tableMeta = wepsTable.getMeta();
        
        //Set the datsource for the table.  The meta should not be needed by the datasource.  Columns are linked to the meta
        //automatically by the datasource.columnlabel == meta.column.datakey.  The meta is passed here so a dynamic testing
        //source may be created.
        wepsTable.setDataSource(new Data(tableMeta));
    }
    
    private void init(){
        
        mi_SI.setSelected(true);
        mi_US.setSelected(!mi_SI.isSelected());
        wepsTable.setUnitsSystem(usda.weru.util.Util.SIUnits);
    }
    
    /** 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() {

        tablePanel = new javax.swing.JPanel();
        wepsTable = new usda.weru.util.table.WepsTable();
        JMB_main = new javax.swing.JMenuBar();
        mnu_Table = new javax.swing.JMenu();
        mi_close = new javax.swing.JMenuItem();
        mnu_Units = new javax.swing.JMenu();
        mi_SI = new javax.swing.JRadioButtonMenuItem();
        mi_US = new javax.swing.JRadioButtonMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Table Preview");

        tablePanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout tablePanelLayout = new javax.swing.GroupLayout(tablePanel);
        tablePanel.setLayout(tablePanelLayout);
        tablePanelLayout.setHorizontalGroup(
            tablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(wepsTable, javax.swing.GroupLayout.DEFAULT_SIZE, 758, Short.MAX_VALUE)
        );
        tablePanelLayout.setVerticalGroup(
            tablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(wepsTable, javax.swing.GroupLayout.DEFAULT_SIZE, 545, Short.MAX_VALUE)
        );

        mnu_Table.setText("Table");

        mi_close.setText("Close");
        mi_close.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mi_closeActionPerformed(evt);
            }
        });
        mnu_Table.add(mi_close);

        JMB_main.add(mnu_Table);

        mnu_Units.setText("Units");

        mi_SI.setText("SI");
        mi_SI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mi_SIActionPerformed(evt);
            }
        });
        mnu_Units.add(mi_SI);

        mi_US.setText("US");
        mi_US.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mi_USActionPerformed(evt);
            }
        });
        mnu_Units.add(mi_US);

        JMB_main.add(mnu_Units);

        setJMenuBar(JMB_main);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tablePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tablePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        setSize(new java.awt.Dimension(790, 626));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents
    
    private void mi_USActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mi_USActionPerformed
        mi_SI.setSelected(!mi_US.isSelected());
        wepsTable.setUnitsSystem(usda.weru.util.Util.USUnits);
    }//GEN-LAST:event_mi_USActionPerformed
    
    private void mi_SIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mi_SIActionPerformed
        mi_US.setSelected(!mi_SI.isSelected());
        wepsTable.setUnitsSystem(usda.weru.util.Util.SIUnits);
    }//GEN-LAST:event_mi_SIActionPerformed
    
    private void mi_closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mi_closeActionPerformed
        dispose();
        throw new RuntimeException("exit");
    }//GEN-LAST:event_mi_closeActionPerformed
    
    
    
    /**
     * @param args You can pass the file name of the xml table to use.
     */
    public static void main(final String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (args.length > 0 ){
                    TablePreview tp = new TablePreview(args[0]);
                    try {
                        if (args.length > 1){
                            String className = args[1];
                            Class<?> c;
                            
                            c = Class.forName(className);
                            
                            Object source = null;
                            try { source = c.getDeclaredConstructor().newInstance(); }
                            catch(NoSuchMethodException | InvocationTargetException e) { }
                            tp.wepsTable.setDataSource((TableDataModel)source);
                        }
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    tp.setVisible(true);
                } else{
                    new TablePreview(null).setVisible(true);
                }
            }
        });
    }
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    protected javax.swing.JMenuBar JMB_main;
    protected javax.swing.JRadioButtonMenuItem mi_SI;
    protected javax.swing.JRadioButtonMenuItem mi_US;
    protected javax.swing.JMenuItem mi_close;
    protected javax.swing.JMenu mnu_Table;
    protected javax.swing.JMenu mnu_Units;
    protected javax.swing.JPanel tablePanel;
    protected usda.weru.util.table.WepsTable wepsTable;
    // End of variables declaration//GEN-END:variables
    
    static class XmlFileFilter extends FileFilter{
        @Override
        public boolean accept(java.io.File f) {
            return f.isDirectory() || f.getName().trim().endsWith(".xml");
        }
        
        @Override
        public String getDescription() {
            return "XML Table Definition";
        }
    }
}
