package Database;

import static Config.SomeCodes.LocalDateTimeToString;
import static Config.SomeCodes.ValidString;

import org.tinylog.Logger;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.List;

public class Sqlite {

    /**
     * create SQLite database for photos
     */
    public Sqlite(){
        CreateDatabase();
    }

    private void CreateDatabase(){
        try{
            Connection conn = GetConnection();
            if (conn != null){
                Statement stmt = conn.createStatement();
                String str = "CREATE TABLE IF NOT EXISTS photos "+
                " (id INTEGER PRIMARY KEY AUTOINCREMENT, DateTime TEXT, Prefix TEXT, FileLeft90 TEXT, FileLeft45 TEXT, FileCenter TEXT, FileRight45 TEXT, FileRight90 TEXT, ThumbLeft90 TEXT, ThumbLeft45 TEXT, ThumbCenter TEXT, ThumbRight45 TEXT, ThumbRight90 TEXT)";
                stmt.execute(str);
                conn.close();
                Logger.info("Database created successfully");
            }
        } catch (Exception e){
            Logger.error("Error creating database: "+e.getMessage());
        }
    }

    /**
     * Insert PhotoReviewClass object to database
     * @param pr PhotoReviewClass object
     */
    public void Insert(PhotoReviewClass pr){
        if (pr!=null){
//            System.out.println("Inserting PhotoReviewClass");
//            System.out.println(pr);
            Insert(pr.getPrefix(), pr.getFileLeft90(), pr.getFileLeft45(), pr.getFileCenter(), pr.getFileRight45(), pr.getFileRight90(), pr.getThumbLeft90(), pr.getThumbLeft45(), pr.getThumbCenter(), pr.getThumbRight45(), pr.getThumbRight90());
        }
    }



    /**
     * Get all PhotoReviewClass object from database
     * @return array of PhotoReviewClass object if success, or null if failed
     */
    public PhotoReviewClass[] GetAll(){
        try{
            Connection conn = GetConnection();
            if (conn != null){
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT * FROM photos");
                List<PhotoReviewClass> list = new java.util.ArrayList<>();
                while (rs.next()){
                    list.add(new PhotoReviewClass(rs.getInt("id"), rs.getString("DateTime"), rs.getString("Prefix"), rs.getString("FileLeft90"), rs.getString("FileLeft45"), rs.getString("FileCenter"), rs.getString("FileRight45"), rs.getString("FileRight90"), rs.getString("ThumbLeft90"), rs.getString("ThumbLeft45"), rs.getString("ThumbCenter"), rs.getString("ThumbRight45"), rs.getString("ThumbRight90")));
                }
                conn.close();
                Logger.info("GetAll success, result count: "+list.size());
                return list.toArray(new PhotoReviewClass[0]);
            } else Logger.info("GetAll failed, connection is null");
        } catch (Exception e){
            Logger.error("Error getting data: "+e.getMessage());
        }
        return null;
    }

    /**
     * Delete all data from database
     */
    @SuppressWarnings("unused")
    public void DeleteAll(){
        try{
            Connection conn = GetConnection();
            if (conn != null){
                Statement stmt = conn.createStatement();
                stmt.execute("DELETE FROM photos");
                conn.close();
                Logger.info("DeleteAll success");
            } else Logger.info("DeleteAll failed, connection is null");
        } catch (Exception e){
            Logger.error("Error deleting data: "+e.getMessage());
        }
    }

    /**
     * Insert data to database
     * @param prefix Prefix
     * @param fileLeft90 FileLeft90
     * @param fileLeft45 FileLeft45
     * @param fileCenter FileCenter
     * @param fileRight45 FileRight45
     * @param fileRight90 FileRight90
     * @param thumbLeft90 ThumbLeft90
     * @param thumbLeft45 ThumbLeft45
     * @param thumbCenter ThumbCenter
     * @param thumbRight45 ThumbRight45
     * @param thumbRight90 ThumbRight90
     */
    private void Insert(String prefix, String fileLeft90, String fileLeft45, String fileCenter, String fileRight45, String fileRight90, String thumbLeft90, String thumbLeft45, String thumbCenter, String thumbRight45, String thumbRight90){
        try{
            Connection conn = GetConnection();
            if (conn != null){
//                System.out.println("Inserting data");
//                System.out.println("prefix: "+prefix);
//                System.out.println("fileLeft90: "+fileLeft90);
//                System.out.println("fileLeft45: "+fileLeft45);
//                System.out.println("fileCenter: "+fileCenter);
//                System.out.println("fileRight45: "+fileRight45);
//                System.out.println("fileRight90: "+fileRight90);

                PreparedStatement stmt = conn.prepareStatement("INSERT INTO photos (DateTime, Prefix, FileLeft90, FileLeft45, FileCenter, FileRight45, FileRight90, ThumbLeft90, ThumbLeft45, ThumbCenter, ThumbRight45, ThumbRight90 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                stmt.setString(1, LocalDateTimeToString(LocalDateTime.now()));
                stmt.setString(2, ValidString(prefix)?prefix:"");
                stmt.setString(3, ValidString(fileLeft90)?fileLeft90:"");
                stmt.setString(4, ValidString(fileLeft45)?fileLeft45:"");
                stmt.setString(5, ValidString(fileCenter)?fileCenter:"");
                stmt.setString(6, ValidString(fileRight45)?fileRight45:"");
                stmt.setString(7, ValidString(fileRight90)?fileRight90:"");
                stmt.setString(8, ValidString(thumbLeft90)?thumbLeft90:"");
                stmt.setString(9, ValidString(thumbLeft45)?thumbLeft45:"");
                stmt.setString(10, ValidString(thumbCenter)?thumbCenter:"");
                stmt.setString(11, ValidString(thumbRight45)?thumbRight45:"");
                stmt.setString(12, ValidString(thumbRight90)?thumbRight90:"");
                stmt.execute();
                conn.close();
                Logger.info("Data inserted successfully");
            } else Logger.info("Insert failed, connection is null");
        } catch (Exception e){
            Logger.error("Error inserting data: "+e.getMessage());
        }
    }

    /**
     * Get Database Connection
     * @return Connection object if success, or null if failed
     */
    private Connection GetConnection(){
        String dbPath = "jdbc:sqlite:database.db";
        try{
            return DriverManager.getConnection(dbPath);
        } catch (Exception e){
            Logger.error("Error connecting to database: "+e.getMessage());
        }
        return null;
    }

}
