package WorkoutDatesUpdater;

import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import static WorkoutDatesUpdater.logging.*;

public class Main {
    private static final HashMap<String, String> dbData;

    static {
        try {
            dbData = getDBData();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws ClassNotFoundException, SQLException, java.text.ParseException, IOException, InterruptedException {
        checkLogExists();
        setLog("Util started", true, false);
        if (checkDate()){
            java.util.Date newDate = calculateDate();
            String[] newDates = generateDates(newDate);
            try (Connection connection = connectToDB()){
                int rowsUpdated = 0;
                for (int i = 0; i < newDates.length; i++){
                    String sql = "UPDATE workout.dates SET date = ? WHERE (id = ?);";
                    PreparedStatement statement = connection.prepareStatement(sql);
                    statement.setString(1, newDates[i]);
                    statement.setInt(2, i+1);
                    rowsUpdated += statement.executeUpdate();
                    setLog("Rows updated: " + rowsUpdated, true, false);
                    statement.close();
                }
                connection.close();
                setLog("Connection closed: " + connection.isClosed(), true, false);
            } catch (SQLException e){
                logException(e);
            }
        }
        setLog("Util ended", true, false);
    }

    public static String[] generateDates(java.util.Date monday){
        String[] newDatesList = new String[14];
        SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy");
        for (int i = 0; i < 14; i++){
            java.util.Date date = new Date(monday.getTime() + i*86400000);
            newDatesList[i] = df.format(date);
            System.out.println(newDatesList[i]);
        }
        return newDatesList;
    }

    public static java.util.Date calculateDate(){
        java.util.Date currentDate = new java.util.Date(System.currentTimeMillis());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        while (dayOfWeek != 2) {
            long newD = currentDate.getTime() - 86400000;
            currentDate = new Date(newD);
            calendar.setTime(currentDate);
            dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        }
        return currentDate;
    }

    public static HashMap<String, String> getDBData() throws IOException {
        JSONParser jsonParser = new JSONParser();
        HashMap<String, String> dbData = new HashMap<>();
        try (FileReader reader = new FileReader("config.json")){
            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
            String dbName = (String) jsonObject.get("dbname");
            dbData.put("dbName", dbName);
            String dbPort = (String) jsonObject.get("dbport");
            dbData.put("dbPort", dbPort);
            String dbUser = (String) jsonObject.get("dbuser");
            dbData.put("dbUser", dbUser);
            String dbPass = (String) jsonObject.get("dbpass");
            dbData.put("dbPass", dbPass);
            String dbScheme = (String) jsonObject.get("schemename");
            dbData.put("dbScheme", dbScheme);
        } catch (IOException | ParseException e) {
            logException(e);
        }
        return dbData;
    }

    public static boolean checkDate() throws SQLException, java.text.ParseException, IOException {
        java.util.Date currentDate = new java.util.Date(System.currentTimeMillis());
        setLog("Current date: " + currentDate, true, false);
        Connection connection = connectToDB();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("SELECT * FROM workout.dates WHERE id = 14;");
        resultSet.next();
        String dbDateString = resultSet.getString("date");
        SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy");
        java.util.Date dbDate = df.parse(dbDateString);
        setLog("DB date: " + dbDate, true, false);
        dbDate = new Date(dbDate.getTime() + 86400000);
        resultSet.close();
        statement.close();
        connection.close();
        setLog("Connection closed: " + connection.isClosed(), true, false);
        setLog("Current date is after DB date: " + currentDate.after(dbDate), true, false);
        return currentDate.after(dbDate);
    }

    public static Connection connectToDB() throws SQLException, IOException {
        Connection connection = null;
        try {
            String url = "jdbc:mysql://" + dbData.get("dbName") + ":" + dbData.get("dbPort") + "/" + dbData.get("dbScheme");
            setLog("Trying to connect to the DB at " + url, true, false);
            connection = DriverManager.getConnection(url, dbData.get("dbUser"), dbData.get("dbPass"));
        } catch (SQLException e) {
            logException(e);
        }
        return connection;
    }

}