import ac
import acsys
import time
from third_party.acdynamicers_sim_info import SimInfo
from os.path import dirname, exists, join
from os import mkdir
import ctypes
from ra_libs.sim_info import SimInfo
import playsound
from playsound import playsound
import threading
import os
from ctypes import wintypes

# Variables globales para rastrear el estado del juego y daños
appWindow = None
labels_danio = []
flagPit = 0
flagQualy = 0
flagRace = 0
flagBlueFlag = 0
timer = 0.0
flagBeforeRace = 0
old_damage = [0., 0., 0., 0.]
old = [0., 0., 0., 0., 0.]
tiempo_vuelta_previo = None
NUMERO_PARTES = 4

def acMain(ac_version):
    global appWindow, labels_danio, tiempo_vuelta_previo
    appWindow = ac.newApp("acofflinechamp")
    ac.setSize(appWindow, 200, 200)
    for i in range(NUMERO_PARTES):
        label = ac.addLabel(appWindow, "Daño Parte {}: 0.00".format(i + 1))
        ac.setPosition(label, 10, 30 + (30 * i))
        labels_danio.append(label)
    tiempo_vuelta_previo = ac.getCarState(0, acsys.CS.LapTime)
        # Obteniendo la carpeta de documentos del usuario y la ruta deseada
    documentos_path = os.path.join(os.path.expanduser('~'), 'Documents', 'Assetto Corsa', 'cfg')
    # Creando y escribiendo en el archivo estadosrn.ini
    with open(os.path.join(documentos_path, 'estadosrn.ini'), 'w') as file:
        file.write('iniciado')
    # Creando y escribiendo en el archivo final.ini
    with open(os.path.join(documentos_path, 'final.ini'), 'w') as file:
        file.write('no')
    return "acofflinechamp"

def acUpdate(deltaT):
    global flagPit, old, flagRace, flagQualy, flagBlueFlag, timer, flagBeforeRace, labels_danio, tiempo_vuelta_previo
    info = SimInfo()
    damage = info.physics.carDamage
    tiempo_vuelta_actual = ac.getCarState(0, acsys.CS.LapTime)
    

    # In pit sound
    if flagPit == 0 and ac.isCarInPitlane(0) == 1:
        flagPit = 1
        play = False
        for i in damage:
            if i > 0.:
                play = True
                ac.log(str(i))
                break
        
        if play:  # if there's some damage starts that's a lot of damage
            ac.log("Pit in")
            #play_sound('golpe.mp3')
            guardar_datos_de_danio(damage)
            threading.Thread(target=lambda: playsound("apps\\python\\acofflinechamp\\sounds\\golpe.mp3")).start()

        else:  # else start in in in in team radio
            ac.log("in in in")
            #play_sound('inin.wav')
            threading.Thread(target=lambda: playsound("apps\\python\\acofflinechamp\\sounds\\inin.wav")).start()

    elif ac.isCarInPitlane(0) != 1 and flagPit == 1:
        flagPit = 0

    # End of race sound
    if ac.getCarState(0, acsys.CS.RaceFinished) == 1 and flagRace == 0 and info.graphics.session == 2:
        flagRace = 1
        ac.log("Grazie Ragazzi")
        #play_sound('grazieRagazzi.wav')
        threading.Thread(target=lambda: playsound("apps\\python\\acofflinechamp\\sounds\\grazieRagazzi.wav")).start()
        documentos_path = os.path.join(os.path.expanduser('~'), 'Documents', 'Assetto Corsa', 'cfg')
        final_path = os.path.join(documentos_path, 'final.ini')
        with open(final_path, 'w') as file:
            file.write('si')

    elif ac.getCarState(0, acsys.CS.RaceFinished) != 1 and flagRace == 1:
        flagRace = 0

    # Damage
    for x, i in enumerate(damage):
        if i > old[x]:
            old[x] = i
            ac.log(str(i) + " , " + str(old[x]))
            ac.log("crashed EDU1")
            #play_sound('golpe.mp3')
            guardar_datos_de_danio(damage)
            threading.Thread(target=lambda: playsound("apps\\python\\acofflinechamp\\sounds\\golpe.mp3")).start()
            if time.time() - timer > 1:
                timer = time.time()
                #play_sound('golpe.mp3')
        elif i == 0. and old[x] > 0.:
            old[x] = 0.

    # Pole position sound
    if info.graphics.session == 1 and info.graphics.position == 1 and flagQualy == 0:
        flagQualy = 1
        ac.log("P1 seb")
        #play_sound('polePosition.wav')
        threading.Thread(target=lambda: playsound("apps\\python\\acofflinechamp\\sounds\\polePosition.wav")).start()
    
    elif info.graphics.session == 1 and info.graphics.position != 1 and flagQualy == 1:
        flagQualy = 0
    
    # Blue flag song
    if info.graphics.flag == 1 and flagBlueFlag == 0:
        flagBlueFlag = 1
        ac.log("Blue flag seb")
        #play_sound('blueFlag.wav')
        threading.Thread(target=lambda: playsound("apps\\python\\acofflinechamp\\sounds\\blueFlag.wav")).start()
    
    elif info.graphics.flag != 1 and flagBlueFlag == 1:
        flagBlueFlag = 0

    # Tomma che t'avvevo detto pre-race
    if flagBeforeRace == 0 and info.graphics.session == 2:
        flagBeforeRace = 1
        #play_sound('beforeRace.wav')
        threading.Thread(target=lambda: playsound("apps\\python\\acofflinechamp\\sounds\\beforeRace.wav")).start()

        
    
    elif flagBeforeRace == 1 and info.graphics.session != 2:
        flagBeforeRace = 0
    
    # Actualizar las etiquetas con los datos de daño actuales
    for i, label in enumerate(labels_danio):
        if i < len(damage):
            ac.setText(label, "Daño Parte {}: {:.2f}".format(i + 1, damage[i]))
    
 

    # Actualizar etiquetas de daño
    update_damage_labels(damage) 

    # Verifica si el tiempo de vuelta era mayor que 2000 y ahora es 0
    if tiempo_vuelta_previo > 2000 and tiempo_vuelta_actual == 0:
        cerrar_assetto_corsa()

    tiempo_vuelta_previo = tiempo_vuelta_actual
    update_damage_labels(damage)

def cerrar_assetto_corsa():
    try:
        ac.log("Cerrando Assetto Corsa") 
        threading.Thread(target=lambda: playsound("apps\\python\\acofflinechamp\\sounds\\forbiddenrestart.mp3")).start()
        time.sleep(1)
        # Ruta al archivo estadosrn.ini
        documentos_path = os.path.join(os.path.expanduser('~'), 'Documents', 'Assetto Corsa', 'cfg')
        estadosrn_path = os.path.join(documentos_path, 'estadosrn.ini')

        # Asegurándose de que el archivo existe
        if os.path.exists(estadosrn_path):
            with open(estadosrn_path, 'w') as file:
                file.write('reseteado')
        else:
            print("El archivo estadosrn.ini no existe o no se encontró.")

        #os.system("taskkill /f /im acs.exe")
    except Exception as e:
        ac.log("Error al intentar cerrar Assetto Corsa: {}".format(e))

def update_damage_labels(damage):
    global labels_danio
    for i, label in enumerate(labels_danio):
        if i < len(damage):
            ac.setText(label, "Daño Parte {}: {:.2f}".format(i + 1, damage[i]))
            ac.setVisible(label, False)


# (aquí incluyes el resto de tus funciones como guardar_datos_de_danio, get_documents_path, etc.)

# Recuerda incluir aquí cualquier otra función o lógica que tengas en tu script actual.


def guardar_datos_de_danio(damage):
    path = get_documents_path()
    out_folder = join(path, "Assetto Corsa", "out")
    if not exists(out_folder):
        mkdir(out_folder)
    with open(join(out_folder, "daniosvrs.txt"), "w") as file:
        for d in damage:
            file.write("{}\n".format(d))

def get_documents_path():
    CSIDL_PERSONAL = 5  # My Documents 
    SHGFP_TYPE_CURRENT = 0  # Get default value
    buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
    ctypes.windll.shell32.SHGetFolderPathW(None, CSIDL_PERSONAL, None, SHGFP_TYPE_CURRENT, buf)
    return buf.value

def acShutdown():
    # Aquí puedes agregar cualquier código de limpieza o cierre
    cerrar_assetto_corsa()
    return
