 /* Copyright 2012 Yaqiang Wang,
 * yaqiang.wang@gmail.com
 * 
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at
 * your option) any later version.
 * 
 * This library 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 Lesser
 * General Public License for more details.
 */
package org.meteoinfo.geo.gui;

 import com.formdev.flatlaf.extras.FlatSVGIcon;

 /**
 *
 * @author yaqiang
 */
public class FrmMeasurement extends javax.swing.JDialog {

    public enum MeasureTypes {
        /// <summary>
        /// Length
        /// </summary>

        Length,
        /// <summary>
        /// Area
        /// </summary>
        Area,
        /// <summary>
        /// Feature
        /// </summary>
        Feature
    }
    // <editor-fold desc="Variables">
    private MeasureTypes _measureType;
    private boolean _isArea;
    private double _previousValue;
    private double _currentValue;
    private double _totalValue;
    private Double areaValue = null;
    private String _unitStr;
    // </editor-fold>
    // <editor-fold desc="Constructor">

    /**
     * Creates new form FrmMeasurement
     * @param parent Parent form
     * @param modal Model or not
     */
    public FrmMeasurement(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        this.setTitle("Measurement");
    }

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

        jToolBar1 = new javax.swing.JToolBar();
        jButton_Feature = new javax.swing.JButton();
        jButton_Distance = new javax.swing.JButton();
        jButton_Area = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jLabel1 = new javax.swing.JLabel();
        jComboBox_Units = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea_Content = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        //jButton_Feature.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/TSB_Feature.Image.png"))); // NOI18N
        jButton_Feature.setIcon(new FlatSVGIcon("org/meteoinfo/icons/measurement.svg"));
        jButton_Feature.setToolTipText("Feature");
        jButton_Feature.setFocusable(false);
        jButton_Feature.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton_Feature.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton_Feature.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_FeatureActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton_Feature);

        //jButton_Distance.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/TSB_Distance.Image.png"))); // NOI18N
        jButton_Distance.setIcon(new FlatSVGIcon("org/meteoinfo/icons/new-line.svg"));
        jButton_Distance.setToolTipText("Distance");
        jButton_Distance.setFocusable(false);
        jButton_Distance.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton_Distance.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton_Distance.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DistanceActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton_Distance);

        //jButton_Area.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/TSB_Area.Image.png"))); // NOI18N
        jButton_Area.setIcon(new FlatSVGIcon("org/meteoinfo/icons/area.svg"));
        jButton_Area.setToolTipText("Area");
        jButton_Area.setFocusable(false);
        jButton_Area.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton_Area.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton_Area.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AreaActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton_Area);
        jToolBar1.add(jSeparator1);

        jLabel1.setText("Units:");
        jToolBar1.add(jLabel1);

        jComboBox_Units.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox_Units.setMinimumSize(new java.awt.Dimension(30, 24));
        jComboBox_Units.setPreferredSize(new java.awt.Dimension(40, 24));
        jComboBox_Units.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox_UnitsActionPerformed(evt);
            }
        });
        jToolBar1.add(jComboBox_Units);
        jComboBox_Units.getAccessibleContext().setAccessibleName("");
        jComboBox_Units.getAccessibleContext().setAccessibleDescription("");

        jTextArea_Content.setColumns(20);
        jTextArea_Content.setRows(5);
        jScrollPane1.setViewportView(jTextArea_Content);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        this.jComboBox_Units.removeAllItems();
        this.jComboBox_Units.addItem("Meters");
        this.jComboBox_Units.addItem("Kilometers");
        this.jComboBox_Units.setSelectedItem("Kilometers");
        _unitStr = "Kilometers";

        this.jButton_Feature.doClick();
        this.jTextArea_Content.setText("");
        this._previousValue = 0;
        this._currentValue = 0;
        this._totalValue = 0;
    }//GEN-LAST:event_formWindowOpened

    private void jButton_FeatureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_FeatureActionPerformed
        // TODO add your handling code here:
        this.jButton_Feature.setSelected(true);
        this.jButton_Area.setSelected(false);
        this.jButton_Distance.setSelected(false);

        _measureType = MeasureTypes.Feature;
        this.jTextArea_Content.setText("");
        this._previousValue = 0;
        this._currentValue = 0;
        this._totalValue = 0;
    }//GEN-LAST:event_jButton_FeatureActionPerformed

    private void jButton_AreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AreaActionPerformed
        // TODO add your handling code here:
        this.jButton_Feature.setSelected(false);
        this.jButton_Area.setSelected(true);
        this.jButton_Distance.setSelected(false);

        _measureType = MeasureTypes.Area;
        _isArea = true;
        this.jTextArea_Content.setText("");
        this._previousValue = 0;
        this._currentValue = 0;
        this._totalValue = 0;
    }//GEN-LAST:event_jButton_AreaActionPerformed

    private void jButton_DistanceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DistanceActionPerformed
        // TODO add your handling code here:
        this.jButton_Feature.setSelected(false);
        this.jButton_Area.setSelected(false);
        this.jButton_Distance.setSelected(true);

        _measureType = MeasureTypes.Length;
        _isArea = false;
        this.jTextArea_Content.setText("");
        this._previousValue = 0;
        this._currentValue = 0;
        this._totalValue = 0;
    }//GEN-LAST:event_jButton_DistanceActionPerformed

    private void jComboBox_UnitsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_UnitsActionPerformed
        // TODO add your handling code here:
        if (this.jComboBox_Units.getItemCount() > 0) {
            _unitStr = this.jComboBox_Units.getSelectedItem().toString();
        }
    }//GEN-LAST:event_jComboBox_UnitsActionPerformed

    // </editor-fold>
    // <editor-fold desc="Get Set Methods">
    /**
     * Get measure type
     *
     * @return Measure type
     */
    public MeasureTypes getMeasureType() {
        return _measureType;
    }

    /**
     * Get if is area
     *
     * @return Boolean
     */
    public boolean isArea() {
        return _isArea;
    }

    /**
     * Set if is area
     *
     * @param istrue Boolean
     */
    public void setArea(boolean istrue) {
        _isArea = istrue;
        this.areaValue = null;
    }

    /**
     * Get previous value
     *
     * @return Previous value
     */
    public double getPreviousValue() {
        return _previousValue;
    }

    /**
     * Set previous value
     *
     * @param value Previous value
     */
    public void setPreviousValue(double value) {
        _previousValue = value;
    }

    /**
     * Get current value
     *
     * @return Current value
     */
    public double getCurrentValue() {
        return _currentValue;
    }

    /**
     * Set current value
     *
     * @param value Current value
     */
    public void setCurrentValue(double value) {
        _currentValue = value;
        showValue();
    }

    /**
     * Get total value
     *
     * @return Total value
     */
    public double getTotalValue() {
        return _totalValue;
    }

    /**
     * Set total value
     *
     * @param value Total value
     */
    public void setTotalValue(double value) {
        _totalValue = value;
    }
    
    /**
     * Get area value
     * @return Area value
     */
    public double getAreaValue(){
        return this.areaValue;
    }
    
    /**
     * Set area value
     * @param value Area value
     */
    public void setAreaValue(double value){
        this.areaValue = value;
    }

    // </editor-fold>
    // <editor-fold desc="Methods">
    private double convertValue(double aValue) {
        return convertValue(aValue, this._isArea);
    }
    
    private double convertValue(double aValue, boolean isArea) {
        double bValue = aValue;
        if (_unitStr.equals("Kilometers")) {
            if (isArea) {
                bValue = aValue / 1000000;
            } else {
                bValue = aValue / 1000;
            }
        }

        return bValue;
    }

    private void showValue() {
        String unitStr = _unitStr;
        String tStr = "Length";
        String lines;
        double currentValue = convertValue(_currentValue);

        if (_isArea) {
            unitStr = unitStr + "^2";
            lines = "Area: " + String.format("%1$,f", currentValue) + " " + unitStr;
        } else {
            lines = "Segement " + tStr + ": " + String.format("%1$,f", currentValue) + " " + unitStr;
            _totalValue = _previousValue + _currentValue;
            lines = lines + "\nTotal " + tStr + ": " + String.format("%1$,f", convertValue(_totalValue))
                    + " " + unitStr;
            if (this.areaValue != null){
                unitStr = unitStr + "^2";
                double area = this.convertValue(this.areaValue, true);
                lines = lines + "\nArea: " + String.format("%1$,f", area) + " " + unitStr;
            }
        }
        this.jTextArea_Content.setText(lines);
    }
    // </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmMeasurement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                FrmMeasurement dialog = new FrmMeasurement(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_Area;
    private javax.swing.JButton jButton_Distance;
    private javax.swing.JButton jButton_Feature;
    private javax.swing.JComboBox jComboBox_Units;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JTextArea jTextArea_Content;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables
}
