package org.example;

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

/**
 * Sample Java program that imports data from an Excel file to MySQL database.
 *
 * @author Nam Ha Minh - https://www.codejava.net
 *
 */
public class example {

    public static void main(String[] args) {
        String jdbcURL = "jdbc:mysql://localhost:3306/sales";
        String username = "user";
        String password = "password";

        String excelFilePath = "Students.xlsx";

        int batchSize = 20;

        Connection connection = null;

        try {
            long start = System.currentTimeMillis();

            FileInputStream inputStream = new FileInputStream(excelFilePath);

            Workbook workbook = new XSSFWorkbook(inputStream);

            Sheet firstSheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = firstSheet.iterator();

            connection = DriverManager.getConnection(jdbcURL, username, password);
            connection.setAutoCommit(false);

            String sql = "INSERT INTO students (name, enrolled, progress) VALUES (?, ?, ?)";
            PreparedStatement statement = connection.prepareStatement(sql);

            int count = 0;

            rowIterator.next(); // skip the header row

            while (rowIterator.hasNext()) {
                Row nextRow = rowIterator.next();
                Iterator<Cell> cellIterator = nextRow.cellIterator();

                while (cellIterator.hasNext()) {
                    Cell nextCell = cellIterator.next();

                    int columnIndex = nextCell.getColumnIndex();

                    switch (columnIndex) {
                        case 0:
                            String name = nextCell.getStringCellValue();
                            statement.setString(1, name);
                            break;
                        case 1:
                            Date enrollDate = nextCell.getDateCellValue();
                            statement.setTimestamp(2, new Timestamp(enrollDate.getTime()));
                        case 2:
                            int progress = (int) nextCell.getNumericCellValue();
                            statement.setInt(3, progress);
                    }

                }

                statement.addBatch();

                if (count % batchSize == 0) {
                    statement.executeBatch();
                }

            }

            workbook.close();

            // execute the remaining queries
            statement.executeBatch();

            connection.commit();
            connection.close();

            long end = System.currentTimeMillis();
            System.out.printf("Import done in %d ms\n", (end - start));

        } catch (IOException ex1) {
            System.out.println("Error reading file");
            ex1.printStackTrace();
        } catch (SQLException ex2) {
            System.out.println("Database error");
            ex2.printStackTrace();
        }

    }
public String loadSheetInDatabase(String inputFile) {
    try {
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));

        // Get first sheet from the workbook
        XSSFSheet sheet = wb.getSheetAt(0);

        Row row;
        Cell cell;

        // Iterate through each rows from first sheet
        Iterator < Row > rowIterator = sheet.iterator();

        Boolean parsedHeaders = false;
        List < String > headers = new ArrayList < String > ();
        List < String > rowValues = null;
        while (rowIterator.hasNext()) {
            row = rowIterator.next();
            if (parsedHeaders) {
                rowValues = new ArrayList <String> ();
            }
            // System.out.println ("Row No.: " + row.getRowNum ());
            // For each row, iterate through each columns
            Iterator < Cell > cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {
                cell = cellIterator.next();
                if (!parsedHeaders) {
                    headers.add(cell.getStringCellValue());
                } else {
                    rowValues.add(cell.getStringCellValue());
                }
            }
            if(!parsedHeaders){
                parsedHeaders = true;
            }else{
                String rowValuesString = "";
                for(String fieldValue : rowValues){
                    rowValuesString += fieldValue + " ";
                }
                System.out.println(rowValuesString);
                InsertRowInDB(headers, rowValues);
                System.out.println("");
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return "success";
}

    public void InsertRowInDB(List<String> headers, List<String> values) throws SQLException, ClassNotFoundException {

        Class.forName("org.postgresql.Driver");
        System.out.println("connected");
        Connection conn = DriverManager.getConnection("jdbc:postgresql:postgres", "postgres", "sridevi");

        String insertColumns = "";
        String preparedStatementClause = "";
        for(int i = 0; i < headers.size(); i++){
            String fieldValue = headers.get(i);
            insertColumns += fieldValue;
            preparedStatementClause += "?";
            if(i <= (headers.size() - 1)){
                insertColumns += ", ";
                preparedStatementClause += ", ";
            }
        }


        String query = String.format( "Insert into excel(%s) values(%s)" , insertColumns, preparedStatementClause);
        PreparedStatement ps = conn.prepareStatement(query);
        for(int i = 0; i < values.size(); i++){
            ps.setString(i, values.get(i));
        }
        ps.executeUpdate();
        System.out.println("Values Inserted Successfully");
    }
}

/*
package org.example;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
/**
 * Hello world!
 *

public class App {
    public static void main(String[] args) {
        System.out.println("Hello World!");

        String excelFilePath = "D:\\maven project\\src\\main\\java\\Arjun Novo - Rotavator.xlsx";
        loadSheetInDatabase(excelFilePath);
    }

    public static String loadSheetInDatabase(String inputFile) {
        try {
            XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));

            // Get first sheet from the workbook
            XSSFSheet sheet = wb.getSheetAt(0);

            Row row;
            Cell cell;

            // Iterate through each rows from first sheet
            Iterator<Row> rowIterator = sheet.iterator();

            Boolean parsedHeaders = false;
            List<String> headers = new ArrayList<String>();
            List<String> rowValues = null;
            while (rowIterator.hasNext()) {
                row = rowIterator.next();
                if (parsedHeaders) {
                    rowValues = new ArrayList<String>();
                }
                // System.out.println ("Row No.: " + row.getRowNum ());
                // For each row, iterate through each columns
                Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext()) {
                    cell = cellIterator.next();
                    if (!parsedHeaders) {
                        headers.add(cell.getStringCellValue());
                    } else {
                        rowValues.add(cell.getStringCellValue());
                    }
                }
                if (!parsedHeaders) {
                    parsedHeaders = true;
                } else {
                    String rowValuesString = "";
                    for (String fieldValue : rowValues) {
                        rowValuesString += fieldValue + " ";
                    }
                    System.out.println(rowValuesString);
                    InsertRowInDB(headers, rowValues);
                    System.out.println("");
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return "success";
    }

    public static void InsertRowInDB(List<String> headers, List<String> values) throws SQLException, ClassNotFoundException {

        Class.forName("org.postgresql.Driver");
        System.out.println("connected");
        Connection conn = DriverManager.getConnection("jdbc:postgresql:postgres", "postgres", "postgres");

        String insertColumns = "";
        String preparedStatementClause = "";
        for(int i = 0; i < headers.size(); i++){
            String fieldValue = headers.get(i);
            insertColumns += fieldValue;
            preparedStatementClause += "?";
            if(i <= (headers.size() - 1)){
                insertColumns += ", ";
                preparedStatementClause += ", ";
            }
        }


        String query = String.format( "Insert into excel(%s) values(%s)" , insertColumns, preparedStatementClause);
        PreparedStatement ps = conn.prepareStatement(query);
        for(int i = 0; i < values.size(); i++){
            ps.setString(i, values.get(i));
        }
        ps.executeUpdate();
        System.out.println("Values Inserted Successfully");
    }
}
 */

