/*
 A basic implementation of the JFrame class.
 */
package usda.weru.weps;

import de.schlichtherle.truezip.file.TFile;
import java.awt.Component;
import java.awt.EventQueue;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.beans.*;

import java.io.PrintWriter;
import java.util.*;
import javax.swing.JComponent;

import usda.weru.util.*;

/**
 * This class build the configuration panel GUI that allows the user to initialize and 
 * modify all settings needed for the WEPS application.
 * @author  manmohan
 */
public class ConfigPanel extends usda.weru.weps.gui.ConfigPanel_n implements PropertyChangeListener {

    private static final long serialVersionUID = 1L;

    /**
     * Default constructor for the Configuration Panel GUI object that helps the
     * user in setting various paths like executables, directories such as management, 
     * soil, database, etc along with the miscellaneous factors like setting units,etc.
     */
    public ConfigPanel() {

    }

    /**
     *
     * @param weps
     */
    public ConfigPanel(Weps weps) {
        super();
        addPropertyChangeListener(weps.cd);
        addPropertyChangeListener(weps.rfd);

        //weps.cd.addPropertyChangeListener(this);
        weps.cd.fireAll(this);

        Util.loadToolTips(this, new TFile("cfg", "tooltips.cfg"));
    }

    /**
     *
     * @param evt
     */
    protected void JTF_runsLocationsJTFManTemp_focusLost(java.awt.event.FocusEvent evt) {
        JTF_runsLocationsJTFManTemp_actionPerformed(null);
    }

    /**
     *
     * @param evt
     */
    protected void JTF_runsLocationsJTFManTemp_actionPerformed(java.awt.event.ActionEvent evt) {
        firePropertyChange(ConfigData.DefaultRunsLocationTemplate, null, JTF_runsLocations.getText());
        firePropertyChange(RunFileData.RunsLocation, null, "NULL");
    }

    /**
     * This button gets the GUI related help from java help provided in the application.
     * @param evt This button accepts the help request from any particular region of the GUI's components.
     */
    @Override
    public void JB_Help_ActionPerformed(java.awt.event.ActionEvent evt) {
    }

    /**
     * This method recognises the change in status or property of the components
     * in various containers that are registered to be tracked for any changes with
     * configuration panel and eventually react to those events.
     * @param e This parameter that decides where the event was triggered and from which component so 
     * that changes could be made to update other registered screens.
     */
    @Override
    public void propertyChange(PropertyChangeEvent e) {

        propertyLoader.loadData(e.getPropertyName(), e.getNewValue() != null ? e.getNewValue().toString() : "");

        if (e.getPropertyName().equals(ConfigData.FormatOperationDate)) {
            String elementValue = (String) e.getNewValue();
            if (elementValue == null) {
                return;
            }
            String keyValue;
            String toCompare;
            Iterator<String> iKeys = optionsDateFormat.keySet().iterator();
            while (iKeys.hasNext()) {
                keyValue = iKeys.next();
                toCompare = optionsDateFormat.get(keyValue);
                if (toCompare.equals(elementValue)) {
                    JCB_formatOperationDate.setSelectedItem(keyValue);
                }
            }
        }
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void exitForm(java.awt.event.WindowEvent evt) {
        this.setVisible(false);

        if (PW_debug != null) { // ignore -- only valid is standalone test mode
            PW_debug.close();
        }
    }
    PrintWriter PW_debug = null;

    /**
     *
     * @param b
     */
    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        applyParameterErrorColoring(this);
    }

    /**
     *
     * @param b
     * @param goToError
     */
    public void setVisible(boolean b, boolean goToError) {
        setVisible(b);
        if (goToError) {
            //find the first tab with errors
            final JComponent c = c_componentsWithErrors.size() > 0 ? c_componentsWithErrors.get(0) : null;
            if (c != null) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        Component c2 = c;
                        boolean setTab = false;
                        while (c2 != null || !setTab) {
                            try {
                                JTP_main.setSelectedComponent(c2);
                                setTab = true;
                            } catch (Exception e) {
                                //ignore it
                            }
                            c2 = c2.getParent();
                        }
                        c.requestFocusInWindow();
                    }
                });
            }

        }
    }

    /**
     * Entry point for stand alone testing.
     * @param args
     */
    static public void main(String args[]) {
        final ConfigPanel cp = new ConfigPanel();
        cp.setVisible(true);
        ConfigData cd = ConfigData.getDefault();
        cd.fireAll(cp);
        cd.load(new TFile("cfg/weps.cfg"), null);
        try {
            cp.PW_debug = new PrintWriter(new TFile("test/configpanel.txt"));
        } catch (FileNotFoundException ex) {
            java.util.logging.Logger.getLogger(ConfigPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        cd.addPropertyChangeListener(cp);
        cp.addPropertyChangeListener(cd);
        cp.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                cp.PW_debug.println(evt.getPropertyName() + " >> " + evt.getNewValue().toString());
            }
        });
        cd.fireAll(cp);
        cp.PW_debug.printf("\nStarting screen test\n\n");
    }
}
