import sys
import time
import discord
import re

import sqlite3

def wheretaken(message : discord.message, reverse):
    if reverse == True:
        reverse = -1
    else:
        reverse = 1

    total_distance = 0
    total_points = 0
    total_games = 0

    sync_time = 0
    new_sync_time = (int)(time.mktime(message.created_at.timetuple()))

    conn = sqlite3.connect('stats.db')
    cursor = conn.cursor()

    cursor.execute('''SELECT * FROM WHERETAKEN WHERE NAME = ?''', (message.author.id,))

    data = cursor.fetchone()

    if data:
        total_games = data[1]
        total_distance = data[2]
        total_points = data[4]
        sync_time = data[6]
        if sync_time > new_sync_time and reverse == 1:
            return

    distances, points = parse_distances_and_points(message.content)
    avg_distance = calculate_average(distances)

    total_distance += avg_distance * reverse
    total_points += sum(points) * reverse
    total_games += 1 * reverse 
    

    average_distance = total_distance / total_games
    average_points = total_points / total_games

    cursor.execute('''INSERT OR REPLACE INTO WHERETAKEN VALUES(?, ?, ?, ?, ?, ?, ?)''',
                   (message.author.id,
                    total_games,
                    total_distance,
                    average_distance,
                    total_points,
                    average_points,
                    new_sync_time
                    ))
    
    conn.commit()
    conn.close()

def whentaken(message : discord.message, reverse):
    if reverse == True:
        reverse = -1
    else:
        reverse = 1

    total_distance = 0
    total_points = 0
    total_games = 0
    total_years = 0

    sync_time = 0
    new_sync_time = (int)(time.mktime(message.created_at.timetuple()))

    conn = sqlite3.connect('stats.db')
    cursor = conn.cursor()

    cursor.execute('''SELECT * FROM WHENTAKEN WHERE NAME = ?''', (message.author.id,))

    data = cursor.fetchone()

    if data:
        total_games = data[1]
        total_distance = data[2]
        total_points = data[4]
        total_years = data[6]
        sync_time = data[8]
        if sync_time > new_sync_time and reverse == 1:
            return

    distances, points, years = parse_distances_points_years(message.content)
    avg_distance = calculate_average(distances)
    avg_years = calculate_average(years)

    total_years += avg_years
    total_distance += avg_distance * reverse
    total_points += sum(points) * reverse
    total_games += 1 * reverse 
    

    average_distance = total_distance / total_games
    average_points = total_points / total_games
    average_years = total_years / total_games

    cursor.execute('''INSERT OR REPLACE INTO WHENTAKEN VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)''',
                   (message.author.id,
                    total_games,
                    total_distance,
                    average_distance,
                    total_points,
                    average_points,
                    total_years,
                    average_years,
                    new_sync_time
                    ))
    
    conn.commit()
    conn.close()


def parse_distances_points_years(message):
    pattern = r'.{4}([0-9]*\.?[0-9]+)([A-Za-z]?) ([A-Za-z]+) - ..([0-9]+) yrs - .([0-9]+)/200'
    matches = re.findall(pattern, message)

    converted_distances = []
    points = []
    years = []

    for distance, thousands, unit, year, point in matches:
        # Convert distance to float
        distance = float(distance)

        # Handle 'K' (thousands) notation
        if thousands:
            distance *= 1000  # Convert K to actual kilometers

        # If the unit is meters, convert to kilometers
        if unit == 'm':
            distance /= 1000  # Convert meters to kilometers

        # Store the distance and corresponding points
        converted_distances.append(distance)
        points.append(int(point))
        years.append(int(year))

    return converted_distances, points, years

def parse_distances_and_points(message):
    # Find all the distances in the format of 'xxx km' or 'xxx m' and their corresponding points
    pattern = r'(\d+(\.\d+)?)\s*(km|m|K)\s*(km)?\s*[^a-zA-Z0-9]*\s*(\d+)\s*/\s*\d+'
    matches = re.findall(pattern, message)

    converted_distances = []
    points = []

    for distance, _, unit, _, point in matches:
        # Convert distance to float
        distance = float(distance)

        # Handle 'K' (thousands) notation
        if unit == 'K':
            distance *= 1000  # Convert K to actual kilometers

        # If the unit is meters, convert to kilometers
        elif unit == 'm':
            distance /= 1000  # Convert meters to kilometers

        # Store the distance and corresponding points
        converted_distances.append(distance)
        points.append(int(point))

    return converted_distances, points

def calculate_average(distances):
    # Calculate the average of the distances
    if distances:
        return sum(distances) / len(distances)
    return 0