/*
 * 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 static findingproduct.SearchScreen.listType;
import static findingproduct.SearchScreen.path;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.Product;
import model.SearchItem;

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

    /**
     * Creates new form ResultScreen
     */
    public static final String DB_ENG = "mydatabase-eng.db";
    public static final double CONVERT_MM_TO_INCH = 0.039370;
    Product mProduct;
    SearchItem mSearchItem;
    ArrayList<Product> listProduct = new ArrayList<>();
    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 == ?)";
    ButtonGroup group;
    boolean isInchSelected, isEnglish;
    String dbName = "mydatabase-eng.db";

    public ResultScreen(SearchItem searchItem, Product product) {
        initComponents();
        mSearchItem = searchItem;
        mProduct = product;
//        ImageIcon icon1 = new ImageIcon("D:\\2.jpg");
        ImageIcon icon1 = new ImageIcon(mSearchItem.getImageUrl());
        jLabel1.setIcon(new ImageIcon(icon1.getImage().getScaledInstance(220, 220, Image.SCALE_DEFAULT)));
        jLabel2.setText(mSearchItem.getTypeName());

        group = new ButtonGroup();
        group.add(rdInch);
        group.add(rdMM);
        isInchSelected = searchItem.isIsInchSelected();
        if (isInchSelected) {
            rdInch.setSelected(true);
        } else {
            rdMM.setSelected(true);
        }
        isEnglish = searchItem.isIsEnglish();
        if(isEnglish){
            rdMM.setText("Millimeter");
            rdInch.setText("Inch");
        }else{
            rdMM.setText("Millimètre");
            rdInch.setText("Pouce");
        }

//        jTable2.setModel(DbUtils.resultSetToTableModel(myRs));
        setResizable(false);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                dispose();
            }
        });

        getData(mSearchItem.isIsEnglish(), mSearchItem.isIsInchSelected());
    }

    private void getData(boolean isEnglish, boolean isInchSelected) {
        //get Data
        try (Connection conn = this.connect();
                PreparedStatement ps = conn.prepareStatement(sqlSearch)) {
            ps.setInt(1, mSearchItem.getTypeId());
            ps.setDouble(2, mProduct.getBore());
            ps.setDouble(3, mProduct.getOutside());
            ps.setDouble(4, mProduct.getWidth());
            ResultSet rs = ps.executeQuery();

//            jTable2.setModel(DbUtils.resultSetToTableModel(rs));
            listProduct.clear();

            while (rs.next()) {
                String design = rs.getString("designation");
                double bore = rs.getDouble("bore");
                double outside = rs.getDouble("outside");
                double width = rs.getDouble("width");

                int count = 0;
                if (bore == mProduct.getBore()) {
                    count += 1;
                }
                if (outside == mProduct.getOutside()) {
                    count += 1;
                }
                if (width == mProduct.getWidth()) {
                    count += 1;
                }
                System.out.println(bore + " - " + outside + " - " + width);
                System.out.println(mProduct.getBore() + " - " + mProduct.getOutside() + " - " + mProduct.getWidth());
                listProduct.add(new Product(bore, outside, width, design, count));
            }

            //sort data    
            Collections.sort(listProduct, Collections.reverseOrder());

            conn.close();

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

        //change depend on Language
        String[] arr;
        arr = new String[4];
        if (isEnglish) {
            arr = new String[] {"Designation", "Bore Diameter", "Outside Diameter", "Width"};
        } else {
            arr = new String[] {"Designation", "Diamètre d'alésage", "Diamètre extérieur", "Épaisseur"};
        }

        DefaultTableModel model = new DefaultTableModel(arr, 0);

        listProduct.forEach((t) -> {
            Vector vec = new Vector();
            vec.add(t.getDesingation());
            if (isInchSelected) {
                vec.add(t.getBore() * CONVERT_MM_TO_INCH);
                vec.add(t.getOutside() * CONVERT_MM_TO_INCH);
                vec.add(t.getWidth() * CONVERT_MM_TO_INCH);
            } else {
                vec.add(t.getBore());
                vec.add(t.getOutside());
                vec.add(t.getWidth());
            }

            model.addRow(vec);
        });

        jTable2.setModel(model);
    }

    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;
    }

    /**
     * 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();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        rdMM = new javax.swing.JRadioButton();
        rdInch = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable2.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
        jTable2.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"
            }
        ));
        jScrollPane2.setViewportView(jTable2);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("jLabel2");

        rdMM.setText("Millimeter");
        rdMM.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdMMActionPerformed(evt);
            }
        });

        rdInch.setText("Inch");
        rdInch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdInchActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 998, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(387, 387, 387)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(rdMM)
                .addGap(18, 18, 18)
                .addComponent(rdInch)
                .addGap(19, 19, 19))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)
                .addGap(10, 10, 10)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rdMM)
                    .addComponent(rdInch))
                .addGap(5, 5, 5)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

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

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

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

    /**
     * @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(ResultScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(ResultScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(ResultScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(ResultScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new ResultScreen().setVisible(true);
//            }
//        });
//    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable2;
    private javax.swing.JRadioButton rdInch;
    private javax.swing.JRadioButton rdMM;
    // End of variables declaration//GEN-END:variables
}
