/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package plcalc;

import java.lang.reflect.Field;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner.*;
import javax.swing.*;
import java.util.*;

/**
 *
 * @author lutusp
 */
public class Units extends JPanel {

    PLCalcMainPanel parent;
    UnitDatum[] currentInputUnit = null;
    JButton[] unitButton;
    JButton oldButton = null;
    int inputUnitIndex = 0;
    

    public Units(PLCalcMainPanel p) {
        parent = p;
        parent.outputUnitsList.setCellRenderer(new MyListCellRenderer());
        int rowLength = 6;
        Field[] fields = UnitData.class.getDeclaredFields();
        Arrays.sort(fields, new MyFieldsComparator());
        unitButton = new JButton[fields.length];
        for (int i = 0; i < fields.length; i++) {
            JButton button = new JButton(fields[i].getName());
            unitButton[i] = button;
            GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = i % rowLength;
            gridBagConstraints.gridy = 0;
            gridBagConstraints.weightx = 1;
            gridBagConstraints.weighty = 1;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            switch (i / rowLength) {
                case 0:
                    parent.unitsButtonPanel1.add(button, gridBagConstraints);
                    break;
                case 1:
                    parent.unitsButtonPanel2.add(button, gridBagConstraints);
                    break;
            }
            button.addMouseListener(new java.awt.event.MouseAdapter() {

                @Override
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    unitsMouseClicked(evt);
                }
            });
        }
        selectInputUnit(unitButton[3]);
        acceptConversion();
    }

    void setBoldFont(Component c, boolean bold) {
        Font f = c.getFont();
        Font nf = f.deriveFont((bold) ? Font.BOLD : Font.PLAIN);
        c.setFont(nf);
    }

    void selectInputUnit(JButton button) {
        inputUnitIndex = 0;
        setBoldFont(button, true);
        if (oldButton != null) {
            setBoldFont(oldButton, false);
        }
        oldButton = button;
        String name = button.getText();
        //System.out.println(name);
        try {
            Field field = UnitData.class.getDeclaredField(name);
            currentInputUnit = (UnitDatum[]) field.get(UnitData.class);
        //System.out.println(currentInputUnit[0]);
        } catch (Exception e) {
            System.out.println(getClass().getName() + ":selectInputUnit: " + e);
        }
        acceptConversion();
    }

    public void setInputUnit() {
        inputUnitIndex = parent.outputUnitsList.getSelectedIndex();
        acceptConversion();
    }

    public void manageKeyTyped(KeyEvent evt) {
        if (evt.getKeyChar() == '\n') {
            acceptConversion();
        }
    }

    void acceptConversion() {
        parent.inputUnitLabel.setText("<html><b>Input Unit: " + getUnitString() + "</b></html>");
        double v = 0;
        try {
            v = parent.getDouble(parent.unitsInputField.getText());
            performConversion(v);
        } catch (NumberFormatException e) {
            parent.beep();
        }
    }

    String getUnitString() {
        UnitDatum[] array = currentInputUnit;
        UnitDatum input = array[inputUnitIndex];
        return input.name;
    }

    void performConversion(double iv) {
        if (currentInputUnit != null) {
            DefaultListModel model = new DefaultListModel();
            parent.outputUnitsList.setModel(model);
            UnitDatum[] array = currentInputUnit;
            UnitDatum input = array[inputUnitIndex];
            double im = input.m;
            double ib = input.b;
            String outs, outn;
            int len = 0;
            for (int i = 0; i < array.length; i++) {
                int tl = array[i].name.length();
                len = (tl > len) ? tl : len;
            }
            int w = parent.outputListScrollPane.getViewport().getWidth();
            w -= parent.outputListScrollPane.getVerticalScrollBar().getWidth();
            FontMetrics f = parent.outputUnitsList.getFontMetrics(parent.outputUnitsList.getFont());
            int cw = f.charWidth('0');
            for (int i = 0; i < array.length; i++) {
                double om = array[i].m;
                double ob = array[i].b;
                double v = (((iv - ib) / im) * om) + ob;
                String fmts = " %-" + len + "s";
                outs = String.format(fmts, array[i].name);
                int ww = w - outs.length() * cw;
                String fmtn = parent.getCurrentFormat();
                outn = parent.specialFormat(fmtn, v);
                // manage this tricky numeric display mode
                if (parent.isAllFormat()) {
                    int q = parent.getDecPlaces() + 4;
                    int p = outn.indexOf(parent.radixChar);
                    if (p == -1) {
                        outn += parent.radixChar + "0";
                    }
                    p = outn.indexOf(parent.radixChar);
                    q -= (outn.length() - p);

                    while (q-- > 0) {
                        outn += " ";
                    }
                }
                while (outn.length() * cw < ww) {
                    outn = " " + outn;
                }
                model.addElement(outs + outn);
            }
            parent.outputUnitsList.setSelectedIndex(inputUnitIndex);
        }
    }

    void unitsMouseClicked(MouseEvent evt) {
        selectInputUnit((JButton) evt.getComponent());
        acceptConversion();
    }
}
