import time
import threading
import subprocess

from flask import Flask, render_template_string, send_file
from flask_sock import Sock

app = Flask(__name__)
sock = Sock(app)

AUDIO_FILE = "sound.mp3"
COOLDOWN_SECONDS = 30

last_trigger_time = 0
out_of_office = False
clients = set()


def broadcast_status():
    """Send current availability status to all connected clients."""

    status = "OUT_OF_OFFICE" if out_of_office else "AVAILABLE"

    dead_clients = []

    for client in clients:
        try:
            client.send(status)
        except:
            dead_clients.append(client)

    for client in dead_clients:
        clients.discard(client)


def play_audio():
    try:
        subprocess.run(
            ["afplay", AUDIO_FILE],
            check=False
        )
    except Exception as e:
        print(f"Audio error: {e}")


VISITOR_HTML = """
<!DOCTYPE html>
<html>
<head>
    <title>Visiting DAHL?</title>

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <style>

        html, body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: Arial, Helvetica, sans-serif;
        }

        body {
            background: #3f7fd9;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .container {
            text-align: center;
            padding: 20px;
            width: 100%;
        }

        h1 {
            color: white;
            font-size: clamp(2rem, 5vw, 4rem);
            margin-bottom: 50px;
        }

        #wakeButton {
            background: #ff4fa3;
            color: white;
            border: none;
            border-radius: 30px;
            padding: 40px 80px;
            font-size: clamp(2rem, 4vw, 3.5rem);
            font-weight: bold;
            cursor: pointer;
            box-shadow: 0 8px 20px rgba(0,0,0,0.25);
        }

        #wakeButton:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        #countdown {
            color: white;
            font-size: 2rem;
            font-weight: bold;
            margin-top: 25px;
            min-height: 2.5rem;
        }

    </style>
</head>

<body>

<div class="container">

    <h1 id="title">
        Visiting DAHL? Press for attention.
    </h1>

    <button id="wakeButton">
        Press to wake Robert!
    </button>

    <div id="countdown"></div>

</div>

<script>

const button = document.getElementById("wakeButton");
const title = document.getElementById("title");
const countdown = document.getElementById("countdown");
const chime = new Audio("/sound.mp3");
chime.preload = "auto";

let timerRunning = false;
let outOfOffice = false;

const ws = new WebSocket(
    `ws://${window.location.host}/ws`
);

ws.onmessage = (event) => {

    if (event.data === "OUT_OF_OFFICE") {

        outOfOffice = true;

        title.textContent =
            "Robert is currently unavailable";

        button.textContent =
            "Unavailable";

        button.disabled = true;

        countdown.textContent = "";
    }

    else if (event.data === "AVAILABLE") {

        outOfOffice = false;

        title.textContent =
            "Visiting DAHL? Press for attention.";

        button.textContent =
            "Press to wake Robert!";

        if (!timerRunning) {
            button.disabled = false;
        }
    }
};

button.addEventListener("click", () => {

    if (outOfOffice) {
        return;
    }

    if (ws.readyState !== WebSocket.OPEN) {
        return;
    }

    ws.send("play");

    // Played inside the click handler so iOS/iPad Safari allows it
    chime.currentTime = 0;
    chime.play().catch((err) => console.log("Audio error:", err));

    startCooldown();
});

function startCooldown() {

    if (timerRunning) {
        return;
    }

    timerRunning = true;

    let seconds = 30;

    button.disabled = true;

    countdown.textContent =
        `Ready again in ${seconds}s`;

    const interval = setInterval(() => {

        seconds--;

        if (seconds > 0) {

            countdown.textContent =
                `Ready again in ${seconds}s`;

        } else {

            clearInterval(interval);

            countdown.textContent = "";

            timerRunning = false;

            if (!outOfOffice) {
                button.disabled = false;
            }
        }

    }, 1000);

}

</script>

</body>
</html>
"""


ADMIN_HTML = """
<!DOCTYPE html>
<html>
<head>

<title>DAHL Attention System</title>

<meta name="viewport" content="width=device-width, initial-scale=1">

<style>

body {
    font-family: Arial, sans-serif;
    text-align: center;
    padding-top: 80px;
}

button {
    font-size: 2rem;
    padding: 20px 40px;
    margin: 20px;
}

#status {
    font-size: 2rem;
    margin-bottom: 40px;
}

</style>

</head>

<body>

<h1>DAHL Attention System</h1>

<div id="status">
Current status:
<strong>{{ status }}</strong>
</div>

<form action="/admin/on" method="post">
    <button type="submit">
        Available
    </button>
</form>

<form action="/admin/off" method="post">
    <button type="submit">
        Out Of Office
    </button>
</form>

</body>
</html>
"""


@app.route("/")
def visitor_page():
    return render_template_string(VISITOR_HTML)


@app.route("/sound.mp3")
def sound_file():
    return send_file(AUDIO_FILE, mimetype="audio/mpeg")


@app.route("/admin")
def admin_page():

    status = (
        "Out Of Office"
        if out_of_office
        else "Available"
    )

    return render_template_string(
        ADMIN_HTML,
        status=status
    )


@app.route("/admin/on", methods=["POST"])
def admin_on():

    global out_of_office

    out_of_office = False
    broadcast_status()

    return admin_page()


@app.route("/admin/off", methods=["POST"])
def admin_off():

    global out_of_office

    out_of_office = True
    broadcast_status()

    return admin_page()


@sock.route("/ws")
def websocket(ws):

    global last_trigger_time

    clients.add(ws)

    try:

        if out_of_office:
            ws.send("OUT_OF_OFFICE")
        else:
            ws.send("AVAILABLE")

        while True:

            message = ws.receive()

            if message is None:
                break

            if out_of_office:
                continue

            now = time.time()

            if (
                now - last_trigger_time
                < COOLDOWN_SECONDS
            ):
                continue

            last_trigger_time = now

            threading.Thread(
                target=play_audio,
                daemon=True
            ).start()

    finally:
        clients.discard(ws)


if __name__ == "__main__":

    print()
    print("Visitor page:")
    print("http://localhost:5002")
    print()
    print("Admin page:")
    print("http://localhost:5002/admin")
    print()

    app.run(
        host="0.0.0.0",
        port=5002
    )