import time
import threading
from text2numde import text2num, is_number, sentence2num 
from playsound3 import playsound

timer_thread = None 
timer_stop = threading.Event()
timer_status = "idle"
timer_start = 0
timer_duration = 0


def parse_time(text):
    """
    Wandelt einen deutschen Text wie 'fünf Minuten' in Sekunden um.
    """
    text = text.lower().strip()

    """
    'Eine' folgt sonst mit einem fehler
    """
    text = text.replace("eine ", "ein ").replace("eins ", "ein ")

    try:
        if "sekunde" in text:
            number_text = text.replace("sekunden", "").replace("sekunde", "").strip()
            seconds = text2num(number_text)  # Use text2num from text2numde
            return seconds
        elif "minute" in text:
            number_text = text.replace("minuten", "").replace("minute", "").strip()
            minutes = text2num(number_text)
            return minutes * 60  # Convert minutes to seconds
        elif "stunde" in text:
            number_text = text.replace("stunden", "").replace("stunde", "").strip()
            hours = text2num(number_text)
            return hours * 3600  # Convert hours to seconds
        else:
            # Default: assume seconds
            return text2num(text)  # Convert general text to number (in seconds)
    except ValueError:
        print("Konnte die Zahl nicht erkennen.")
        return None
    

def start_timer(seconds):

    global timer_thread, timer_status, timer_start, timer_duration

    if timer_status == "running":
        return False # timer läuft bereits
    
    timer_stop.clear()
    timer_duration = seconds
    timer_start = time.time()
    timer_status = "running"

    def run():
        global timer_status
        if not timer_stop.wait(seconds):
            timer_status = "finished"
            print("Timer abgelaufen") # """ TTS """
    
    timer_thread = threading.Thread(target=run, daemon=True)
    timer_thread.start()
    return True
""" 
    print(f"Timer startet für {seconds} Sekunden...")
    time.sleep(seconds)
    print("Timer abgelaufen!")
    playsound("/home/tino/Desktop/Abschlussprojekt/test assistant/cloneAssistantAllInOne/RasPi_Voice_Assistant--WIP/clock-alarm-8761.mp3")
    sound.stop()
     """
    
""" # Beispielnutzung
spoken_input = "eine sekunde"  # This could come from a voice assistant
seconds = parse_time(spoken_input)
if seconds:
    start_timer(seconds) """

def stop_timer():
    global timer_status
    if timer_status != "running":
        print("Kein Timer gestellt")
        return False

    timer_stop.set()
    timer_status = "stopped"
    return True  

def timer_status_info():
    if timer_status != "running":
        return {"status": timer_status, "remaining": 0}

    elapsed = time.time() - timer_start
    remaining = max(0, int(timer_duration - elapsed))

    return {
        "status": "running",
        "remaining": remaining
    }

def format_duration(seconds):
    if seconds < 60:
        return f"{seconds} {second_text(seconds)}"

    minutes = seconds // 60
    secs = seconds % 60

    if minutes < 10:
        if secs == 0:
            return f"{minutes} {minute_text(minutes)}"
        return f"{minutes} {minute_text(minutes)} und {secs} {second_text(secs)}"

    if minutes < 60:
        return f"{minutes} {minute_text(minutes)}"
    
    hours = minutes // 60
    mins = minutse % 60

    if mins == 0:
        return f"{hours} {hour_text(hours)}"
    return f"{hours} {hour_text(hours)} und {mins} {minute_text(mins)}"



def minute_text(n):
    return "Minute" if n == 1 else "Minuten"

def second_text(n):
    return "Sekunde" if n == 1 else "Sekunden"

def hour_text(n):
    return "Stunde" if n == 1 else "Stunden"
