/*
 * LocationDialog.java
 *
 * Created on 19 January 2008, 16:24
 */
package uk.co.mccombe.terrain;
import uk.co.mccombe.mapping.*;
import java.awt.Component;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;

/**
 *
 * @author  Mike
 */
public class LocationDialog extends javax.swing.JDialog {

    private PropertySet properties;

    /** Creates new form LocationDialog
     * @param parent
     * @param modal 
     * @param toolbox
     * @param propertyset 
     */
    public LocationDialog(java.awt.Frame parent, boolean modal, MappingToolkit toolbox, PropertySet propertyset) {
        super(parent, modal);
        initComponents();
        toolkit = toolbox;
        properties = propertyset;
        gridRefText.setInputVerifier(new GridRefVerifier());
        ewText.setInputVerifier(new NumericVerifier());
        nsText.setInputVerifier(new NumericVerifier());
        spacingText.setInputVerifier(new NumericVerifier());
        for (int i = 0; i < positions.length; i++) {
            java.net.URL imageURL = TerrainFrame.class.getResource(String.format("images/pos%d.png", i + 1));
            if (imageURL != null) {
                PositionItem pos = new PositionItem(positions[i], new ImageIcon(imageURL));
                posList.addItem(pos);
            }
        }
        posList.setRenderer(new PositionRenderer());
        ourParent = parent ;
    }

    int getReturnStatus() {
        return returnStatus;
    }

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

        gridRefText = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        exampleText = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        coordNameText = new javax.swing.JTextField();
        ewText = new javax.swing.JTextField();
        nsText = new javax.swing.JTextField();
        spacingText = new javax.swing.JTextField();
        posList = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        gridRefText.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        gridRefText.setText("ST430969");

        jLabel1.setText("Grid Reference");

        jLabel2.setText("E-W Range (m)");

        jLabel3.setText("N-S Range (m)");

        jLabel4.setText("Spacing (m)");

        okButton.setText("OK");
        okButton.setPreferredSize(new java.awt.Dimension(65, 23));
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        exampleText.setFont(new java.awt.Font("Arial", 0, 10));
        exampleText.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);

        jLabel5.setText("Selected Coordinate System");

        coordNameText.setEditable(false);
        coordNameText.setHorizontalAlignment(javax.swing.JTextField.TRAILING);

        ewText.setHorizontalAlignment(javax.swing.JTextField.TRAILING);

        nsText.setHorizontalAlignment(javax.swing.JTextField.TRAILING);

        spacingText.setHorizontalAlignment(javax.swing.JTextField.TRAILING);

        posList.setMaximumSize(new java.awt.Dimension(80, 40));

        jLabel6.setText("Grid Ref is at");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 310, Short.MAX_VALUE)
                        .addComponent(posList, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(gridRefText, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)
                            .addComponent(coordNameText, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cancelButton)
                        .addGap(18, 18, 18)
                        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 270, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(spacingText)
                            .addComponent(ewText, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
                            .addComponent(nsText)))
                    .addComponent(exampleText, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(coordNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(gridRefText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(1, 1, 1)
                .addComponent(exampleText, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ewText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nsText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(spacingText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(posList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        doClose(RET_CANCEL);
}//GEN-LAST:event_cancelButtonActionPerformed

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

        GridRefVerifier checker = new GridRefVerifier();
        if (checker.verify(gridRefText)) {
            doClose(RET_OK);
        }
        else {
            javax.swing.JOptionPane.showMessageDialog(ourParent,new String[] {"Incorrect format for grid reference","Please correct or cancel"}, "Warning", javax.swing.JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_okButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                LocationDialog dialog = new LocationDialog(new javax.swing.JFrame(), true, new MappingToolkit(), new PropertySet("terrain.properties", new DefaultProperties()));
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    public String getGridRef() {
        return gridRefText.getText();
    }

    public String getEW() {
        return ewText.getText();
    }

    public void setEW(String t) {
        ewText.setText(t);
    }

    public String getNS() {
        return nsText.getText();
    }

    public void setNS(String t) {
        nsText.setText(t);
    }

    public String getSpacing() {
        return spacingText.getText();
    }

    public void setSpacing(String t) {
        spacingText.setText(t);
    }

    public void setGridRef(String sampleCoordinate) {
        gridRefText.setText(sampleCoordinate);
    }

    public void setExample(String sampleCoordinate) {
        exampleText.setText(sampleCoordinate);
    }

    public void setcoordName(String coordname) {
        coordNameText.setText(coordname);
    }

    public class GridRefVerifier extends InputVerifier {

        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String val = field.getText().trim();
            try {
                String typename = properties.get(TerrainProperties.COORD);
                String ename = properties.get(TerrainProperties.ELLIPSOID);
                String dname = properties.get(TerrainProperties.DATUM);
                Ellipsoid ellipse = toolkit.getEllipsoid(ename);
                Datum datum = toolkit.getDatum(dname);
                CoordinateSystem c = toolkit.makeCoordinateSystem(typename, val, ellipse, datum);
            } catch (Exception ex) {
                return false;
            }
            return true;
        }
    }

    private class NumericVerifier extends InputVerifier {

        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String val = field.getText().trim();
            java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
            java.text.ParsePosition pos = new java.text.ParsePosition(0);
            int n = val.length();
            double x = nf.parse(val, pos).doubleValue();
            if (pos.getIndex() != n) {
                return false;
            }
            field.setText(String.format(formatString, x));
            return true;
        }
    }

    private void doClose(int retStatus) {
        returnStatus = retStatus;
        setVisible(false);
        dispose();

    }

    public int getNSAlignment() {
        int i = posList.getSelectedIndex();
        return verts[i];
    }

    public int getEWAlignment() {
        int i = posList.getSelectedIndex();
        return horzs[i];
    }
    /** A return status code - returned if Cancel button has been pressed */
    public static final int RET_CANCEL = 0;
    /** A return status code - returned if OK button has been pressed */
    public static final int RET_OK = 1;

    private class PositionRenderer extends JLabel implements ListCellRenderer {

        public PositionRenderer() {
            setOpaque(true);
            setHorizontalAlignment(LEADING);
            setVerticalAlignment(CENTER);
        }

        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            PositionItem p = (PositionItem) value;
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            setIcon(p.getIcon());
            setText(p.getText());
            setFont(list.getFont());
            return this;
        }
    }

    public int getAlignment() {
        return posList.getSelectedIndex();
    }

    public void setAlignment(int i) {
        posList.setSelectedIndex(i);
    }

    private class PositionItem {

        public PositionItem(String text, Icon pic) {
            label = text;
            image = pic;
        }

        public Icon getIcon() {
            return image;
        }

        public String getText() {
            return label;
        }
        private Icon image;
        private String label;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextField coordNameText;
    private javax.swing.JTextField ewText;
    private javax.swing.JLabel exampleText;
    private javax.swing.JTextField gridRefText;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField nsText;
    private javax.swing.JButton okButton;
    private javax.swing.JComboBox posList;
    private javax.swing.JTextField spacingText;
    // End of variables declaration//GEN-END:variables
    private int returnStatus = RET_CANCEL;
    private static final String formatString = "%12.2f";
    private MappingToolkit toolkit;
    private String[] positions = {"SW", "S", "SE", "W", "Centre", "E", "NW", "N", "NE"};
    private static final int[] verts = {SwingConstants.BOTTOM, SwingConstants.BOTTOM, SwingConstants.BOTTOM,
        SwingConstants.CENTER, SwingConstants.CENTER, SwingConstants.CENTER,
        SwingConstants.TOP, SwingConstants.TOP, SwingConstants.TOP
    };
    private static final int[] horzs = {SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.RIGHT,
        SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.RIGHT,
        SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.RIGHT
    };
    private java.awt.Frame ourParent ;
}
