#!/usr/bin/env python3
"""Air theremin, Mac side. Reads the distance the Uno prints (cm, one per line)
and passes it to a web page on this Mac that makes the sound. No extra installs.
The Uno's port can only be used by one program: stop this before uploading code."""
import base64
import glob
import json
import os
import select
import termios
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

HTTP_PORT = 8777
PAGE = Path(__file__).resolve().parent / "index.html"
TAKES = Path(__file__).resolve().parent.parent / "takes"
latest = {"cm": None, "n": 0, "at": 0.0}
changed = threading.Condition()


def find_port():
    ports = sorted(glob.glob(os.environ.get("THEREMIN_PORT", "/dev/cu.usbmodem*")))
    return ports[0] if ports else None


def publish(cm):
    with changed:
        latest.update(cm=cm, n=latest["n"] + 1, at=time.time())
        changed.notify_all()


def read_uno():
    while True:
        port, fd = find_port(), None
        try:
            if port:
                fd = os.open(port, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
                a = termios.tcgetattr(fd)
                a[0], a[1], a[3] = 0, 0, 0
                a[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
                a[4] = a[5] = termios.B9600
                termios.tcsetattr(fd, termios.TCSANOW, a)
                buf = b""
                while os.path.exists(port):
                    if not select.select([fd], [], [], 1)[0]:
                        continue
                    chunk = os.read(fd, 1024)
                    if not chunk:
                        break
                    *lines, buf = (buf + chunk).split(b"\n")
                    for line in lines:
                        try:
                            publish(float(line))
                        except ValueError:
                            pass
        except (OSError, termios.error) as error:
            print("Uno:", error, flush=True)
        finally:
            if fd is not None:
                os.close(fd)
        time.sleep(1)


def played_notes(events):
    """Turn the readings of one try into a list of notes: name, start and length in seconds."""
    notes = []
    for event in events:
        name, t = event["note"], event["t"]
        if notes and notes[-1]["end"] is None:
            if notes[-1]["note"] == name:
                continue
            notes[-1]["end"] = t
        if name:
            notes.append({"note": name, "start": t, "end": None})
    if notes and notes[-1]["end"] is None:
        notes[-1]["end"] = events[-1]["t"]
    return [{"note": n["note"], "start": round(n["start"], 2), "seconds": round(n["end"] - n["start"], 2)} for n in notes]


def save_take(take, folder=None):
    """Save one try: the clean sound (.webm) and what was played (.json)."""
    folder = folder or TAKES
    folder.mkdir(exist_ok=True)
    stem = base = time.strftime("take-%m%d-%H%M%S")
    count = 1
    while (folder / f"{stem}.json").exists():
        count += 1
        stem = f"{base}-{count}"
    (folder / f"{stem}.webm").write_bytes(base64.b64decode(take["audio"]))
    data = {"mode": take["mode"], "played": played_notes(take["events"]), "readings": take["events"]}
    (folder / f"{stem}.json").write_text(json.dumps(data, indent=1))
    return stem


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        # JSON only: another website cannot send that here without permission this program never gives.
        size = int(self.headers.get("Content-Length") or 0)
        if self.path != "/take" or self.headers.get("Content-Type") != "application/json" or not 0 < size < 30_000_000:
            self.send_error(400)
            return
        try:
            name = save_take(json.loads(self.rfile.read(size)))
        except (KeyError, ValueError, TypeError, OSError) as error:
            print("Take not saved:", error, flush=True)
            self.send_error(500)
            return
        body = json.dumps({"saved": name}).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path == "/":
            body = PAGE.read_bytes()
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.send_header("Cache-Control", "no-store")
            self.end_headers()
            self.wfile.write(body)
        elif self.path == "/stream":
            self.send_response(200)
            self.send_header("Content-Type", "text/event-stream")
            self.send_header("Cache-Control", "no-store")
            self.end_headers()
            seen = -1
            try:
                while True:
                    with changed:
                        changed.wait_for(lambda: latest["n"] != seen, timeout=1)
                        seen = latest["n"]
                        data = {"cm": latest["cm"], "live": time.time() - latest["at"] < 1.5}
                    self.wfile.write(f"data: {json.dumps(data)}\n\n".encode())
                    self.wfile.flush()
            except (BrokenPipeError, ConnectionResetError):
                pass
        else:
            self.send_error(404)

    def log_message(self, *args):
        pass


def serve(http_port=HTTP_PORT):
    threading.Thread(target=read_uno, daemon=True).start()
    server = ThreadingHTTPServer(("127.0.0.1", http_port), Handler)
    server.daemon_threads = True
    return server


if __name__ == "__main__":
    print(f"Air theremin: http://localhost:{HTTP_PORT}", flush=True)
    serve().serve_forever()
