/*
 * iReport - Visual Designer for JasperReports.
 * Copyright (C) 2002 - 2009 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com
 *
 * Unless you have purchased a commercial license agreement from Jaspersoft,
 * the following license terms apply:
 *
 * This program is part of iReport.
 *
 * iReport is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * iReport is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with iReport. If not, see <http://www.gnu.org/licenses/>.
 */
package com.jaspersoft.ireport.designer.tools;

import com.jaspersoft.ireport.designer.IReportManager;
import com.jaspersoft.ireport.designer.utils.Unit;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 *
 * @author gtoffoli
 */
public class MultiUnitNumberEditor extends javax.swing.JPanel implements ChangeListener {

    private int value = 0;
    private Unit selectedUnit = null;
    private boolean updating = false;

    private List<ChangeListener> changeListeners = new ArrayList<ChangeListener>();

    public void addChangeListener(ChangeListener listener)
    {
        if (!changeListeners.contains(listener))
        {
            changeListeners.add(listener);
        }
    }

    public void removeChangeListener(ChangeListener listener)
    {
        changeListeners.remove(listener);
    }

    /** Creates new form MultiUnitNumberEditor */
    public MultiUnitNumberEditor() {
        initComponents();

        jComboBox1.setModel(new DefaultComboBoxModel(Unit.getStandardUnits()));
        
        String unit = IReportManager.getPreferences().get("Unit","inches");
        int index = Unit.getUnitIndex(unit);
        jComboBox1.setSelectedIndex(index);
        this.selectedUnit = Unit.getStandardUnits()[index];

    }

    private void fireStateChangedEvent() {
        for (ChangeListener listener : changeListeners)
        {
            listener.stateChanged(new ChangeEvent(this));
        }
    }

    /** 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSpinner1 = new javax.swing.JSpinner();
        jComboBox1 = new javax.swing.JComboBox();

        setPreferredSize(new java.awt.Dimension(80, 20));
        setLayout(new java.awt.BorderLayout(4, 0));
        add(jSpinner1, java.awt.BorderLayout.CENTER);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });
        add(jComboBox1, java.awt.BorderLayout.LINE_END);
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed

        if (isUpdating()) return;
        setSelectedUnit((Unit)jComboBox1.getSelectedItem());
    }//GEN-LAST:event_jComboBox1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JSpinner jSpinner1;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the value
     */
    public int getValue() {
        return value;
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        this.jComboBox1.setEnabled(enabled);
        this.jSpinner1.setEnabled(enabled);
    }

    /**
     * @param value the value to set
     */
    public void setValue(int value) {
        if (this.value == value) return;
        this.value = value;
        updateDisplayValue();
        //fireStateChangedEvent();
    }

    public void setSelectedUnit(Unit unit) {

        if (unit.equals(this.selectedUnit)) return;
        
        int index = Unit.getUnitIndex(unit.getKeyName());
        if (jComboBox1.getSelectedIndex() != index)
        {
            jComboBox1.setSelectedIndex(index);
        }

        this.selectedUnit = unit;
        boolean oldState = setUpdating(true);
        jSpinner1.getModel().removeChangeListener(this);
        SpinnerNumberModel snm = null;
        if (unit.getKeyName().equals("pixels"))
        {
            snm = new SpinnerNumberModel(getValue(),0,50000,1);
            jSpinner1.setModel(snm);
        }
        else
        {
            double displayVal = unit.convert(getValue());
            double step = 0.1;
            if (unit.getKeyName().equals("inches")) step = 0.01;
            else if (unit.getKeyName().equals("cm")) step = 0.01;
            else if (unit.getKeyName().equals("cm")) step = 1.0;
            
            snm = new SpinnerNumberModel(displayVal,0,50000.0,step);
            jSpinner1.setModel(snm);
        }
        snm.addChangeListener(this);
        setUpdating(oldState);
    }

    public void updateDisplayValue()
    {
        boolean oldState = setUpdating(true);
        jSpinner1.setValue( getSelectedUnit().convert(getValue()) );
        setUpdating(oldState);
    }

    public void stateChanged(ChangeEvent e) {

        if (isUpdating()) return;
        double d = ((Number)jSpinner1.getModel().getValue()).doubleValue();
        
        int x = (int)getSelectedUnit().toPixel(d);
        if (x != this.value)
        {
            this.value = x;
            fireStateChangedEvent();
        }
    }



    /**
     * @return the selectedUnit
     */
    public Unit getSelectedUnit() {
        return selectedUnit;
    }

    /**
     * @return the updating
     */
    protected boolean isUpdating() {
        return updating;
    }

    /**
     * @param updating the updating to set
     */
    protected boolean setUpdating(boolean updating) {
        boolean b = this.updating;
        this.updating = updating;
        return b;
    }



}
