/*
 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.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.io.FileNotFoundException;
import java.beans.*;

import java.io.PrintWriter;
import java.util.*;
import javax.swing.JComponent;
import javax.swing.JTextField;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

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;
    private static final Logger LOGGER = LogManager.getLogger(ConfigPanel.class);
    
    protected double CSIPSoilPolygonSize;
    protected double CSIPPrismPolygonSize;
    public final ConvertedValue csipSoil = new ConvertedValue(Util.USUnits, "acre");
    protected final ConvertedValue csipPrism = new ConvertedValue(Util.USUnits, "acre");

    /**
     * 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() {

    }

    public ConfigPanel(Weps weps) {
        super();
        addPropertyChangeListener(weps.cd);
        addPropertyChangeListener(weps.rfd);
        
        CSIPSoilPolygonSize = Double.parseDouble(weps.cd.getData("CD-WS-csip-Soil-polygonSize"));
        CSIPPrismPolygonSize = Double.parseDouble(weps.cd.getData("CD-WS-csip-Prism-polygonSize"));
        csipSoil.setValue(CSIPSoilPolygonSize);
        csipPrism.setValue(CSIPPrismPolygonSize);        
        
        csipSoil.addDisplayUnits(Util.SIUnits, "hectare");
        csipPrism.addDisplayUnits(Util.SIUnits, "hectare");
        
        WTF_CSIPSoilPolygonSize.setValueInternal(csipSoil.getValue());
        WTF_CSIPPrismPolygonSize.setValueInternal(csipPrism.getValue());

        //weps.cd.addPropertyChangeListener(this);
        weps.cd.fireAll(this);
        
        Util.loadToolTips(this, new TFile("cfg", "tooltips.cfg"));
        
        // Do this at this point, so that all of the ConfigPData has already been loaded
        manageParameters();
        serverControlInit();
        //System.out.println("New Parent: " + JB_reportFileName.getParent().getName());
        manageCheckBoxes();
        initGis();

    }

    protected void manageCheckBoxes() {
        if(getJTFinfo(9).equals("")) {
            disableCheckBox(22);
        }
        if(getJTFinfo(10).equals("")) {
            disableCheckBox(23);
        }
        if(getJTFinfo(11).equals("")) {
            disableCheckBox(25);
        }
        if(getJTFinfo(12).equals("")) {
            disableCheckBox(26);
        }
        if(getJTFinfo(13).equals("")) {
            disableCheckBox(27);
        }
        if(getJTFinfo(14).equals("")) {
            disableCheckBox(28);
        }
        if(getJTFinfo(3).equals("")) {
            disableCheckBox(18);
        }
        if(getJTFinfo(4).equals("")) {
            disableCheckBox(19);
        }
        if(getJTFinfo(5).equals("")) {
            disableCheckBox(20);
        }
    }
    
    protected void JTF_runsLocationsJTFManTemp_focusLost(java.awt.event.FocusEvent evt) {
        JTF_runsLocationsJTFManTemp_actionPerformed(null);
    }

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

    /**
     * This method recognizes 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);
                }
            }
        } else if (e.getPropertyName().equals(ConfigData.Units)) {
            measurementUnits = e.getNewValue().toString();
            if ("US".equals(measurementUnits)) {
                JL_remoteDataSoilUnits.setText("acres (approx.)");
                JL_remoteDataPrismUnits.setText("acres (approx.)");
            } else {
                JL_remoteDataSoilUnits.setText("hectares (approx.)");
                JL_remoteDataPrismUnits.setText("hectares (approx.)");
            }
            csipSoil.setDisplaySystem(measurementUnits);
            csipPrism.setDisplaySystem(measurementUnits);

            WTF_CSIPSoilPolygonSize.setValueInternal(csipSoil.getDisplayValue());
            WTF_CSIPPrismPolygonSize.setValueInternal(csipPrism.getDisplayValue());

        }
    }

    @Override
    protected void exitForm() {
        this.setVisible(false);

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

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        applyParameterErrorColoring(this);
    }
    
    @Override
    public void WTF_CSIPSoilActionPerformed(ActionEvent evt) {
        csipSoil.setDisplayValue(WTF_CSIPSoilPolygonSize.getValue());
        putChange("CD-WS-csip-Soil-polygonSize", Double.toString(csipSoil.getValue()));
    }
    
    @Override
    public void WTF_CSIPPrismActionPerformed(ActionEvent evt) {
        csipPrism.setDisplayValue(WTF_CSIPPrismPolygonSize.getValue());
        putChange("CD-WS-csip-Prism-polygonSize", Double.toString(csipPrism.getValue()));
    }
    
    @Override
    public void WTF_CSIPSoilFocusLost(FocusEvent evt) {
        WTF_CSIPSoilActionPerformed(null);
    }
    
    @Override
    public void WTF_CSIPPrismFocusLost(FocusEvent evt) {
        WTF_CSIPPrismActionPerformed(null);
    }

    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) {
            LOGGER.log(Level.ERROR, 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");
    }
}
