import os
import time
import configparser
from datetime import datetime
import pygame
import socket
import threading

# Initialize pygame mixer
pygame.mixer.init()

# Dictionary to map phrases to their corresponding sound files
phrase_to_sound = {
    "NORMAL SERVE OUT": "servebeep.wav",
    "CLOSE OUT": "rallybeepclose.wav",
    "SUPER OUT": "rallybeep.wav",
    "NORMAL OUT": "rallybeep.wav",
    "CLOSE SERVE OUT": "servebeep.wav",
    "SUPER SERVE OUT": "servebeepclose.wav"
}

# Function to check if a line contains any of the specified phrases
def check_line(line):
    for phrase in phrase_to_sound.keys():
        if phrase in line:
            return phrase
    return None

# Function to read configuration from the INI file
def read_config():
    config = configparser.ConfigParser()
    config.read("config.ini")
    log_file_path = config.get("Settings", "LogFile")
    court_name = config.get("Settings", "CourtName")
    footfault_file_path = config.get("Settings", "Footfault")
    IP_Relay = config.get("Settings", "IP")
    CommandON = config.get("Settings", "CommandON")
    CommandOFF = config.get("Settings", "CommandOFF")
    
    return log_file_path, court_name, footfault_file_path, IP_Relay, CommandON, CommandOFF

# Function to send the CommandOFF signal after a delay
def send_command_off(IP_Relay, CommandOFF):
    time.sleep(3)
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
        sock.sendto(bytes.fromhex(CommandOFF), (IP_Relay, 8761))

# Function to monitor a log file
def monitor_log_file(log_file_path, court_name, IP_Relay, CommandON, CommandOFF, footfault=False):
    with open(log_file_path, "r") as file:
        # Move the pointer to the end of the file
        file.seek(0, os.SEEK_END)
        while True:
            new_line = file.readline()
            if new_line:
                if footfault:
                    print(f"Footfault detected at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
                    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
                        sock.sendto(bytes.fromhex(CommandON), (IP_Relay, 8761))
                    pygame.mixer.music.load("FootFault4.wav")
                    pygame.mixer.music.play()
                    # Start a new thread to send the CommandOFF after 3 seconds
                    threading.Thread(target=send_command_off, args=(IP_Relay, CommandOFF)).start()
                else:
                    result = check_line(new_line)
                    if result:
                        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        print(f"[{current_time}] {court_name}: {result}")
                        # Play the corresponding sound file
                        pygame.mixer.music.load(phrase_to_sound[result])
                        pygame.mixer.music.play()
            time.sleep(0.1)  # Adjust the sleep time as needed

# Main loop to monitor the log files
log_file_path, court_name, footfault_file_path, IP_Relay, CommandON, CommandOFF = read_config()

# Create a new thread for each log file monitoring
# Thread for the main log file
main_thread = threading.Thread(target=monitor_log_file, args=(log_file_path, court_name, IP_Relay, CommandON, CommandOFF))
main_thread.start()

# Thread for the footfault log file
footfault_thread = threading.Thread(target=monitor_log_file, args=(footfault_file_path, court_name, IP_Relay, CommandON, CommandOFF, True))
footfault_thread.start()
