#!/usr/bin/env python3

from flask import Flask, jsonify, request
from threading import Thread, Event
from time import sleep
import importlib
import os
from PIL import Image
#from lib.display import show
import lib.display

SCENES_DIR = 'scenes'
scenes = {}

for file in os.listdir(SCENES_DIR):
    if file.endswith(".py") and file != "__init__.py":
        module_name = file[:-3]
        print(f"Loading scene: {module_name}")
        module = importlib.import_module(f"{SCENES_DIR}.{module_name}")
        scenes[module_name] = module

app = Flask(__name__)

# Thread and control event
animation_thread = None
stop_event = Event()
#image_buffer = Image.new("RGB", (128, 64))

# Example background animation function
def run_animation(name):
    print(f"Starting animation: {name}")
    t = 0
    while not stop_event.is_set():
        # This is where you'd update your LED matrix or PIL image
        print(f"[{name}] Frame {t}")
        t += 1
        sleep(0.2)  # 5 FPS
    print(f"Animation {name} stopped")

# Utility to start a new animation
def start_animation(scene_name, args):
    global animation_thread, stop_event
    if scene_name not in scenes:
        print(f"Scene '{scene_name}' not found!")
        return

    # Stop previous thread
    if animation_thread and animation_thread.is_alive():
        stop_event.set()
        animation_thread.join()

    # Reset stop event and start new thread
    stop_event.clear()
    animation_thread = Thread(target=scenes[scene_name].start, args=(stop_event, args), daemon=True)
    animation_thread.start()

@app.route("/start/<animation_name>")
def start(animation_name):
    start_animation(animation_name, args=request.args)
    return jsonify({"status": "started", "animation": animation_name})

@app.route("/reset")
def reset():
  lib.display.matrix.matrix.Clear()
  return "ok"

@app.route("/stop")
def stop():
    # Stop running thread
    global animation_thread, stop_event
    if animation_thread and animation_thread.is_alive():
        stop_event.set()
        animation_thread.join()
    # Clear the display
    lib.display.matrix.clear()
    return jsonify({"status": "stopped"})

if __name__ == "__main__":
    app.run(port=6000)
    #app.run(debug=True, port=6000)

