/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.meteoinfo.map.forms;

import java.awt.Cursor;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

import org.meteoinfo.common.PointD;
import org.meteoinfo.geo.analysis.GeoComputation;
import org.meteoinfo.geometry.geoprocess.SpatialQueryTypes;
import org.meteoinfo.geo.layer.LayerTypes;
import org.meteoinfo.geo.layer.MapLayer;
import org.meteoinfo.geo.layer.VectorLayer;
import org.meteoinfo.geometry.shape.PolygonShape;
import org.meteoinfo.geometry.shape.Shape;
import org.meteoinfo.geometry.shape.ShapeTypes;

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

    List<VectorLayer> _vLayers = new ArrayList<>();
    private final FrmMain _frmMain;

    /**
     * Creates new form FrmSelectByLocation
     * @param parent
     * @param modal
     */
    public FrmSelectByLocation(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        _frmMain = (FrmMain) parent;
        for (MapLayer aLayer : _frmMain.getMapDocument().getActiveMapFrame().getMapView().getLayers()) {
            if (aLayer.getLayerType() == LayerTypes.VECTOR_LAYER) {
                _vLayers.add((VectorLayer) aLayer);
            }
        }

        this.jComboBox_FromLayer.removeAllItems();
        for (VectorLayer aLayer : _vLayers) {
            jComboBox_FromLayer.addItem(aLayer.getLayerName());
        }
        jComboBox_FromLayer.setSelectedIndex(0);

        this.jComboBox_SelType.removeAllItems();
        for (SpatialQueryTypes type : SpatialQueryTypes.values()) {
            jComboBox_SelType.addItem(type.toString());
        }
        jComboBox_SelType.setSelectedIndex(0);

        this.jComboBox_RelatedLayer.removeAllItems();
        for (VectorLayer aLayer : _vLayers) {
            jComboBox_RelatedLayer.addItem(aLayer.getLayerName());
        }
        jComboBox_RelatedLayer.setSelectedIndex(0);
    }

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

        jLabel1 = new javax.swing.JLabel();
        jComboBox_FromLayer = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jComboBox_SelType = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jComboBox_RelatedLayer = new javax.swing.JComboBox();
        jCheckBox_SelFeaturesOnly = new javax.swing.JCheckBox();
        jButton_Select = new javax.swing.JButton();
        jButton_Clear = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Select By Location");

        jLabel1.setText("Select features from the layer:");

        jComboBox_FromLayer.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel2.setText("That:");

        jComboBox_SelType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel3.setText("The features in this layer:");

        jComboBox_RelatedLayer.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox_RelatedLayer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox_RelatedLayerActionPerformed(evt);
            }
        });

        jCheckBox_SelFeaturesOnly.setText("Selected features only");

        jButton_Select.setText("Select");
        jButton_Select.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_SelectActionPerformed(evt);
            }
        });

        jButton_Clear.setText("Clear");
        jButton_Clear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_ClearActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jComboBox_FromLayer, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jComboBox_SelType, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(jComboBox_RelatedLayer, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jCheckBox_SelFeaturesOnly)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(85, 85, 85)
                        .addComponent(jButton_Select)
                        .addGap(69, 69, 69)
                        .addComponent(jButton_Clear)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox_FromLayer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox_SelType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox_RelatedLayer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jCheckBox_SelFeaturesOnly)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Select)
                    .addComponent(jButton_Clear))
                .addGap(22, 22, 22))
        );

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

    private void jComboBox_RelatedLayerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_RelatedLayerActionPerformed
        // TODO add your handling code here:
        if (this.jComboBox_RelatedLayer.getItemCount() == 0) {
            return;
        }

        VectorLayer aLayer = _vLayers.get(this.jComboBox_RelatedLayer.getSelectedIndex());
        List<Integer> selIndexes = aLayer.getSelectedShapeIndexes();
        if (selIndexes.size() > 0) {
            this.jCheckBox_SelFeaturesOnly.setEnabled(true);
            this.jCheckBox_SelFeaturesOnly.setText("Selected features only (" + String.valueOf(selIndexes.size())
                    + " features selected)");
        } else {
            jCheckBox_SelFeaturesOnly.setEnabled(false);
            jCheckBox_SelFeaturesOnly.setSelected(false);
            jCheckBox_SelFeaturesOnly.setText("Selected features only");
        }
    }//GEN-LAST:event_jComboBox_RelatedLayerActionPerformed

    private void jButton_SelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SelectActionPerformed
        // TODO add your handling code here:
        if (this.jComboBox_FromLayer.getSelectedItem().toString().equals(this.jComboBox_RelatedLayer.
                getSelectedItem().toString())) {
            JOptionPane.showMessageDialog(null, "The two layers are same!");
            return;
        }

        //---- Show progressbar                      
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        VectorLayer fromLayer = _vLayers.get(this.jComboBox_FromLayer.getSelectedIndex());
        VectorLayer relatedLayer = _vLayers.get(this.jComboBox_RelatedLayer.getSelectedIndex());
        SpatialQueryTypes selType = SpatialQueryTypes.valueOf(this.jComboBox_SelType.getSelectedItem().toString());
        boolean onlySel = this.jCheckBox_SelFeaturesOnly.isSelected();
        switch (selType) {
            case Within:
                if (!relatedLayer.getShapeType().isPolygon()) {
                    JOptionPane.showMessageDialog(null, "The second layer must be polygon layer for 'Within' case!");
                    this.setCursor(Cursor.getDefaultCursor());
                    return;
                } else {
                    for (Shape aShape : fromLayer.getShapes()) {
                        boolean isIn = true;
                        List<PointD> points = (List<PointD>) aShape.getPoints();
                        for (PointD aPoint : points) {
                            if (!GeoComputation.pointInPolygonLayer(relatedLayer, aPoint, onlySel)) {
                                isIn = false;
                                break;
                            }
                        }
                        if (isIn) {
                            aShape.setSelected(true);
                        } else {
                            aShape.setSelected(false);
                        }
                    }
                }
                break;
            case Contain:
                if (fromLayer.getShapeType() != ShapeTypes.POLYGON) {
                    JOptionPane.showMessageDialog(null, "The first layer must be polygon layer for 'Within' case!");
                    this.setCursor(Cursor.getDefaultCursor());
                    return;
                } else {
                    List<Shape> shapes = new ArrayList<>();
                    if (onlySel) {
                        for (Shape aShape : relatedLayer.getShapes()) {
                            if (aShape.isSelected()) {
                                shapes.add(aShape);
                            }
                        }
                    } else {
                        shapes = (List<Shape>) relatedLayer.getShapes();
                    }

                    for (Shape aShape : fromLayer.getShapes()) {
                        aShape.setSelected(false);
                        PolygonShape aPolygon = (PolygonShape) aShape;
                        for (Shape bShape : shapes) {
                            boolean isIn = true;
                            List<PointD> points = (List<PointD>) bShape.getPoints();
                            for (PointD aPoint : points) {
                                if (!GeoComputation.pointInPolygon(aPolygon, aPoint)) {
                                    isIn = false;
                                    break;
                                }
                            }
                            if (isIn) {
                                aShape.setSelected(true);
                                break;
                            }
                        }
                    }
                }
                break;
        }

        _frmMain.refreshMap();

        //---- Hide progressbar                      
        this.setCursor(Cursor.getDefaultCursor());
    }//GEN-LAST:event_jButton_SelectActionPerformed

    private void jButton_ClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ClearActionPerformed
        // TODO add your handling code here:
        VectorLayer fromLayer = _vLayers.get(this.jComboBox_FromLayer.getSelectedIndex());
        fromLayer.clearSelectedShapes();
        _frmMain.refreshMap();
    }//GEN-LAST:event_jButton_ClearActionPerformed

    /**
     * @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 ex) {
            java.util.logging.Logger.getLogger(FrmSelectByLocation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmSelectByLocation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmSelectByLocation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmSelectByLocation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FrmSelectByLocation dialog = new FrmSelectByLocation(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_Clear;
    private javax.swing.JButton jButton_Select;
    private javax.swing.JCheckBox jCheckBox_SelFeaturesOnly;
    private javax.swing.JComboBox jComboBox_FromLayer;
    private javax.swing.JComboBox jComboBox_RelatedLayer;
    private javax.swing.JComboBox jComboBox_SelType;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration//GEN-END:variables
}
