package usda.weru.util;

import java.awt.Component;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.measure.Quantity;
import tec.uom.se.quantity.Quantities;
import javax.measure.Unit;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JRadioButton;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; 
import usda.weru.util.ConfigData.MeasureableConfigurationOption;
import usda.weru.weps.fuel.Fuel;
import usda.weru.weps.fuel.FuelChooser;
import usda.weru.weps.fuel.FuelDAO;
import usda.weru.weps.location.chooser.AllowedStationModeChooser;
import usda.weru.weps.location.chooser.AllowedStationModeChooser.AllowedStationModeChooserLabel;

/**
 *
 * @author wjr
 */
public class LoadProperties {

    private static final Logger LOGGER = LogManager.getLogger(LoadProperties.class);

    private final Map<String, List<Component>> HT_comp = new HashMap<>();

    private void addToTable(String key, Component comp) {
        if (HT_comp.containsKey(key)) {
            List<Component> compVec = HT_comp.get(key);
            compVec.add(comp);
        } else {
            Vector<Component> vec = new Vector<>();
            vec.add(comp);
            HT_comp.put(key, vec);
        }
    }

    private void getChildren(JComponent con) {
        Component[] children = con.getComponents();
        for (Component child : children) {
            String name = child.getName();
            if (!"".equals(name) && name != null) {
                if (name.contains(":")) {
                    name = name.substring(0, name.indexOf(":"));
                }
                addToTable(name, child);
            }
            if (child instanceof JComponent) {
                getChildren((JComponent) child);
            }
        }
    }

    /**
     *
     * @param comp this should always be a JRootPane
     */
    public void setupPropertyHashtable(JComponent comp) {
        getChildren(comp);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public void loadData(String property, String value) {
        List<Component> vec = HT_comp.get(property);
        if (vec == null) {
            // property not found on this form
            return;
        }
        for (Component comp : vec) {
            if (comp instanceof MeasurableField) {
                MeasurableField<?> mf = (MeasurableField) comp;
                MeasureableConfigurationOption option
                        = ConfigData.getDefault().getMeasureableConfigurationOption(mf.getName());
                Unit<?> units = ConfigData.getDefault().getMeasureableUnit(mf.getName());

                if (units != null) {

                    Quantity quantityValue;
                    if (option.isDouble()) {
                        quantityValue = Quantities.getQuantity(Double.valueOf(value), units);
                    } else {
                        quantityValue = Quantities.getQuantity(Long.valueOf(value), units);
                    }

                    if (mf.getUnits() == null) {
                        mf.setUnits(quantityValue.getUnit());
                    }
                    mf.setValue(quantityValue);
                } else {
                    LOGGER.warn("MeasureableConfigurationOption is not set for " + mf.getName());
                }

            } else if (comp instanceof JTextField) {
                ((JTextField) comp).setText(value);
                break;
            } else if (comp instanceof JSpinner) {
                JSpinner jsp = (JSpinner)comp;
                SpinnerModel jspModel = jsp.getModel();
                if (jspModel instanceof SpinnerNumberModel) {
                    jsp.setValue(Integer.parseInt(value));
                } else {
                    jsp.setValue(value);
                }
                break;
            } else if (comp instanceof JComboBox) {
                ((JComboBox) comp).setSelectedItem(value);
                break;
            } else if (comp instanceof JCheckBox) {
                ((JCheckBox) comp).setSelected("1".equals(value.trim()));
            } else if (comp instanceof JRadioButton) {
                JRadioButton jrb = (JRadioButton) comp;
                if (jrb.getName().startsWith("CD-SC-button")) {
                    if (jrb.getText().contentEquals(value)) {
                        jrb.setSelected(true);
                    }
                } else if (jrb.getName().trim().endsWith(value)) {
                    jrb.setSelected(true);
                }
            } else if (comp instanceof AllowedStationModeChooser) {
                AllowedStationModeChooser chooser = (AllowedStationModeChooser) comp;
                if (property.endsWith("allowedmodes")) {
                    chooser.deserializeAllowedModes(value);
                }
                //chooser.deserializeSelectedModes(value);
            } else if (comp instanceof AllowedStationModeChooserLabel) {
                AllowedStationModeChooser chooser = (AllowedStationModeChooser) comp.getParent();
                if (property.endsWith("enabledmodes")) {
                    chooser.deserializeEnabledModes(value);
                } else if (property.endsWith("defaultmode")) {
                    chooser.setDefaultMode(value);
                }
            } else if (comp instanceof FuelChooser) {
                FuelChooser chooser = (FuelChooser) comp;
                Fuel fuel = FuelDAO.getInstance().getFuel(value);
                chooser.setSelectedFuel(fuel);
            }
        }
    }

    public Collection<Component> getComponentsForProperty(String propertyName) {
        return HT_comp.get(propertyName);
    }
}
