package cronjob;

import data.GuiMysql;
import objects.*;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static objects.Constants.*;

public class updateStatistics {
    private static final String USERNAME = "OddsNy";
    private static final String PASSWORD = "Odds1_Ny_Password";
    private static final String DATABASE = "new_odds";
    private static final String URL = "jdbc:mysql://nordh.xyz:3306/";
    private static final String TIMEZONE_FIX = "?useUnicode=true&useJDBCCompliantTimezoneShift=true" +
            "&useLegacyDatetimeCode=false&serverTimezone=UTC";
    Connection conn;

    List<League> leagues = new ArrayList<>();

    public updateStatistics() {
        GuiMysql db = GuiMysql.getInstance();
        leagues.addAll(db.getLeaguesWithPrio());
        List<SoccerMatchAnalysis> matchesToUpdate = getMatchesToUpdate(getLastUpdatedStatisticsDate());

        System.out.println("Matches to update " + matchesToUpdate.size());
        for (SoccerMatchAnalysis match : matchesToUpdate) {
            Optional<League> ol = leagues.stream().filter(f -> f.getLeagueName() == match.getLeagueName()).findFirst();
            League l;
            if (ol.isPresent()) {
                l = ol.get();
            } else {
                System.out.println("League " + match.getLeagueName() + " not found in leagues");
                continue;
            }
            int homeTeamRes = match.scoringTotal(l.getScoringTotal(), true);
            int awayTeamRes = match.scoringTotal(l.getScoringTotal(), false);
            int diff = homeTeamRes - awayTeamRes;
            db.addTotalGoalStat(match,l.getScoringTotal(), l.getLeagueId(), diff);

            homeTeamRes = match.winLossRatio(l.getWinLossRatio(), true);
            awayTeamRes = match.winLossRatio(l.getScoringTotal(), false);
            diff = homeTeamRes - awayTeamRes;
            db.addWinLossRatioStat(match,l.getLeagueId(),l.getScoringTotal(), diff);

            homeTeamRes = match.winLossRatioHomeAndAway(true, l.getWinLossRatioHomeAndAway());
            awayTeamRes = match.winLossRatioHomeAndAway(false, l.getWinLossRatioHomeAndAway());
            diff = homeTeamRes - awayTeamRes;
            db.addWinLossRatioHomeAndAwayStat(match, l.getLeagueId(), l.getWinLossRatioHomeAndAway(), diff);

            diff = match.getScoringDiffLastGames(l.getScoringDiffLastGame());
            db.addScoringDiffLastGamesStatistics(match,l.getLeagueId(), l.getScoringDiffLastGame(), diff);
        }

        updateLastStatsRun(LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
    }

    private void updateLastStatsRun(String date) {
        String sql = "UPDATE Settings SET value = ? WHERE name = 'statisticsUpdated'";
        try (PreparedStatement stat = getConnection().prepareStatement(sql)) {
            stat.setString(1, date);
            stat.executeUpdate();
        }catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new updateStatistics();
    }

    private List<SoccerMatchAnalysis> getMatchesToUpdate(String lastUpdatedStatisticsDate) {
        String sql = "SELECT * FROM SoccerResults WHERE prio = 1 AND DATE(gameDate) > ?";
        List<SoccerMatchAnalysis> result = new ArrayList<>();
        try (PreparedStatement stat = getConnection().prepareStatement(sql)) {
            stat.setString(1, lastUpdatedStatisticsDate);

            ResultSet rs = stat.executeQuery();

            while (rs.next()) {
                SoccerMatchAnalysis sma = new SoccerMatchAnalysis(new SoccerMatch(rs.getInt("id"),
                        GuiMysql.getInstance().getTeam(rs.getInt(HOME_TEAM_ID)),
                        GuiMysql.getInstance().getTeam(rs.getInt(AWAY_TEAM_ID)),
                        rs.getFloat(ODDS_1), rs.getFloat(ODDS_X), rs.getFloat(ODDS_2), rs.getInt(HOME_SCORE),
                        rs.getInt(AWAY_SCORE), LocalDateTime.parse(rs.getString(GAME_DATE)), rs.getString(SEASON)));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }

    public String getLastUpdatedStatisticsDate() {
        String sql = "SELECT value FROM Settings WHERE name = 'statisticsUpdated'";
        String result = "1970-01-01";

        try (PreparedStatement stat = getConnection().prepareStatement(sql)) {
            ResultSet rs = stat.executeQuery();

            while (rs.next()) {
                result = rs.getString("value");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }


    protected Connection getConnection() {
        if (conn == null) {
            try {
                conn = DriverManager.getConnection(URL + DATABASE + TIMEZONE_FIX, USERNAME, PASSWORD);
            } catch (final SQLException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
        return conn;
    }

}
