/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package findingproduct;

import java.awt.Color;
import java.awt.Image;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Vector;
import javafx.scene.control.ToggleGroup;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.text.NumberFormatter;
import model.Product;
import model.SearchItem;
import model.TypeProduct;
import net.proteanit.sql.DbUtils;

/**
 *
 * @author TienNguyen
 */
public class SearchScreen extends javax.swing.JFrame {

    public static ArrayList<TypeProduct> listType = new ArrayList();
    public static String path;
    public static final double CONVERT_INCH_TO_MM = 25.4;
    public static final String DB_ENG = "mydatabase-eng.db";
    public static final String DB_FRA = "mydatabase-fra.db";

    ButtonGroup group;
    ToggleGroup toggleLang;
    //default unit is mm
    double bore = 0, outside = 0, width = 0;
    boolean isInchSelected;
    boolean isEngSelected;
    String dbName = "mydatabase-eng.db";

    /**
     * Creates new form SearchScreen
     */
    public SearchScreen() {
        initComponents();
        String x;
        
        

        rdMM.setSelected(true);
        isInchSelected = false;

        group = new ButtonGroup();
        group.add(rdInch);
        group.add(rdMM);

        jToggleButton1.setSelected(true);
        isEngSelected = true;
//        
//        toggleLang = new ToggleGroup();
//        toggleLang.
        
        ImageIcon icon1 = new ImageIcon(path + "/images/"+"logo.jpg");
        tvLogo.setIcon(new ImageIcon(icon1.getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT)));
        
    }

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

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        menuBar1 = new java.awt.MenuBar();
        menu1 = new java.awt.Menu();
        menu2 = new java.awt.Menu();
        jLabel5 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox<>();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        edt2 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        edt1 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        edt3 = new javax.swing.JTextField();
        jToggleButton1 = new javax.swing.JToggleButton();
        jToggleButton2 = new javax.swing.JToggleButton();
        Search = new javax.swing.JButton();
        rdInch = new javax.swing.JRadioButton();
        rdMM = new javax.swing.JRadioButton();
        lbUnit = new javax.swing.JLabel();
        tvLogo = new javax.swing.JLabel();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        menu1.setLabel("File");
        menuBar1.add(menu1);

        menu2.setLabel("Edit");
        menuBar1.add(menu2);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel5.setText("Type");

        jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jComboBox1.setName(""); // NOI18N
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setText("Searching");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel2.setText("Bore Diameter");

        edt2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        edt2.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        edt2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edt2ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel3.setText("Outside Diameter");

        edt1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        edt1.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel4.setText("Width");

        edt3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        edt3.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jToggleButton1.setText("English");
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        jToggleButton2.setText("Français");
        jToggleButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton2ActionPerformed(evt);
            }
        });

        Search.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        Search.setText("Search");
        Search.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SearchActionPerformed(evt);
            }
        });

        rdInch.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        rdInch.setText("Inch");
        rdInch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdInchActionPerformed(evt);
            }
        });

        rdMM.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        rdMM.setText("Millimeter");
        rdMM.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdMMActionPerformed(evt);
            }
        });

        lbUnit.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        lbUnit.setText("Unit");

        tvLogo.setText("jLabel6");

        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()
                        .addGap(301, 301, 301)
                        .addComponent(Search))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(295, 295, 295)
                        .addComponent(tvLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(302, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jToggleButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jToggleButton2))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel5)
                                    .addComponent(lbUnit))
                                .addGap(35, 35, 35)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(edt1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(edt3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
                                        .addComponent(edt2, javax.swing.GroupLayout.Alignment.TRAILING))
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(rdInch)
                                        .addComponent(rdMM)))))
                        .addGap(90, 90, 90))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(256, 256, 256))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jToggleButton2)
                    .addComponent(jToggleButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addComponent(tvLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(edt1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(edt2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(edt3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(61, 61, 61)
                        .addComponent(lbUnit))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(42, 42, 42)
                        .addComponent(rdMM)
                        .addGap(18, 18, 18)
                        .addComponent(rdInch)))
                .addGap(52, 52, 52)
                .addComponent(Search)
                .addGap(101, 101, 101))
        );

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

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:\


    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void SearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchActionPerformed
        // TODO add your handling code here:
        getSearchingData();

    }//GEN-LAST:event_SearchActionPerformed

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        // TODO add your handling code here:
        if (!isEngSelected) {
            System.out.println("eng");
            jToggleButton2.setSelected(false);
            jToggleButton1.setSelected(true);
            isEngSelected = true;
            dbName = DB_ENG;
            listType.clear();
            //change language label
            jLabel1.setText("Searching");
            jLabel2.setText("Bore Diameter");
            jLabel3.setText("Outside Diameter");
            jLabel4.setText("Width");
            jLabel5.setText("Type");
            lbUnit.setText("Unit");
            Search.setText("Search");
            rdMM.setText("Millimeter");
            rdInch.setText("Inch");
            getData();
        }

    }//GEN-LAST:event_jToggleButton1ActionPerformed

    private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton2ActionPerformed
        // TODO add your handling code here:
        if (isEngSelected) {
            System.out.println("fra");
            jToggleButton2.setSelected(true);
            jToggleButton1.setSelected(false);
            isEngSelected = false;
            dbName = DB_FRA;
            listType.clear();
            //change language label
            jLabel1.setText("Recherche");
            jLabel2.setText("Diamètre d'alésage");
            jLabel3.setText("Diamétre à l'extérieur");
            jLabel4.setText("Épaisseur");
            jLabel5.setText("Type");
            lbUnit.setText("Unité");
            Search.setText("Chercher");
            rdMM.setText("Millimètre");
            rdInch.setText("Pouce");
            getData();
        }
    }//GEN-LAST:event_jToggleButton2ActionPerformed

    private void edt2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edt2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_edt2ActionPerformed

    private void rdMMActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdMMActionPerformed
        // TODO add your handling code here:
        isInchSelected = false;
    }//GEN-LAST:event_rdMMActionPerformed

    private void rdInchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdInchActionPerformed
        // TODO add your handling code here:
        isInchSelected = true;
    }//GEN-LAST:event_rdInchActionPerformed

    private Connection connect() {
        String url = "jdbc:sqlite:" + path + "/database/"+dbName;
//        String url = "jdbc:sqlite:D:\\Working\\Duy\\db\\mydatabase.db";
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return conn;
    }
    
    private Connection connectDefault() {
        String url = "jdbc:sqlite:" + path + "/database/"+DB_ENG;
//        String url = "jdbc:sqlite:D:\\Working\\Duy\\db\\mydatabase.db";
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return conn;
    }

    public void getData() {
        String sql = "Select * from type";
        try (Connection conn = this.connect();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                int typeId = rs.getInt("type_id");
                String typeName = rs.getString("type_name");
                String image = rs.getString("image");
                listType.add(new TypeProduct(typeId, typeName, image));
//                System.out.println(rs.getInt("type_id") + "\t"
//                        + rs.getString("type_name") + "\t"
//                        + rs.getString("image"));
            }
            conn.close();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        
        jComboBox1.removeAllItems();
        listType.forEach((t) -> {
            jComboBox1.addItem(t.getTypeName());
        });
    }

    public void getSearchingData() {
        String sqlSearch = "select designation, bore, outside, width from product join type on product.type_id == type.type_id where type.type_id == ? AND (product.bore == ? or outside == ? or width == ?)";
        String sqlNull = "select designation, bore, outside, width from product join type on product.type_id == type.type_id where type.type_id == ?";
        try {
            bore = Double.parseDouble(edt1.getText());
        } catch (NumberFormatException nfe) {
            edt1.setText("");
        }

        try {
            outside = Double.parseDouble(edt2.getText());
        } catch (NumberFormatException nfe) {
            edt2.setText("");
        }

        try {
            width = Double.parseDouble(edt3.getText());
        } catch (NumberFormatException nfe) {
            edt3.setText("");
        }

        //convert unit if inchSelected
        if (isInchSelected) {
            bore = bore * CONVERT_INCH_TO_MM;
            outside = bore * CONVERT_INCH_TO_MM;
            width = width * CONVERT_INCH_TO_MM;

            //handle data
            bore = (double) Math.round(bore * 1000) / 1000;
            outside = (double) Math.round(outside * 1000) / 1000;
            width = (double) Math.round(width * 1000) / 1000;

        }

        try (Connection conn = this.connectDefault();
                PreparedStatement ps = conn.prepareStatement(sqlSearch)) {
            ps.setInt(1, jComboBox1.getSelectedIndex() + 1);
            ps.setDouble(2, bore);
            ps.setDouble(3, outside);
            ps.setDouble(4, width);
            ResultSet rs = ps.executeQuery();
            System.out.println(ps.toString());

            if (rs.next()) {
                String imageStr = listType.get(jComboBox1.getSelectedIndex()).getImage();
                String typeName = listType.get(jComboBox1.getSelectedIndex()).getTypeName();
                new ResultScreen(new SearchItem(
                        isEngSelected,
                        path + "\\images\\" + imageStr,
                        typeName,
                        isInchSelected, jComboBox1.getSelectedIndex() + 1),
                        new Product(bore, outside, width)
                ).setVisible(true);

            } else {
                JOptionPane.showMessageDialog(new JFrame(), "No data found!", "Notice",
                        JOptionPane.ERROR_MESSAGE);
            }

            conn.close();

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

    }

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

        path = Paths.get(".").normalize().toAbsolutePath().toString();
        SearchScreen searchScreen = new SearchScreen();
        searchScreen.getData();
        
//        searchScreen.listType;

        System.out.println(path.toString());
//        ToggleSwitch ts = new ToggleSwitch();
//        ts.setLocation(5, 135);
//        searchScreen.add(ts);


        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                searchScreen.setResizable(false);
//                searchScreen.getContentPane().setBackground(Color.YELLOW);
                searchScreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                searchScreen.setVisible(true);
               

            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Search;
    private javax.swing.JTextField edt1;
    private javax.swing.JTextField edt2;
    private javax.swing.JTextField edt3;
    private javax.swing.JComboBox<String> jComboBox1;
    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.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JToggleButton jToggleButton2;
    private javax.swing.JLabel lbUnit;
    private java.awt.Menu menu1;
    private java.awt.Menu menu2;
    private java.awt.MenuBar menuBar1;
    private javax.swing.JRadioButton rdInch;
    private javax.swing.JRadioButton rdMM;
    private javax.swing.JLabel tvLogo;
    // End of variables declaration//GEN-END:variables
}
