#!/usr/bin/env python

import argparse
import sys
from typing import Tuple

from bottle import post, request, route, run, static_file, view

from animation import Off
from dmx import DMX, Bar252, StairvilleLedPar56, REDSpot18RGB, ZhennbyPar

room = ''

@route('/')
@view('index')
def index():
    return {'room': room}

@route('/static/<path:path>')
def static(path):
    return static_file(path, root='static')

@route('/api/state')
def state():
    return {
        'animation': dmx.animation,
        'color': rgb_to_hex(dmx.color)
    }

@post('/api/state')
def update():
    json = request.json
    print(json)
    dmx.animation = json["animation"]
    dmx.color = hex_to_rgb(json["color"])
    return state()


def hex_to_rgb(hex: str) -> tuple[int, ...]:
    return tuple(int(hex[i:i+2], 16) for i in (1, 3, 5))


def rgb_to_hex(color: Tuple[int, int, int]) -> str:
    return f"#{color[0]:02X}{color[1]:02X}{color[2]:02X}"

def main(args):
    global dmx, room

    parser = argparse.ArgumentParser(prog='foobazdmx', description='Make the lights flicker.')
    parser.add_argument('-a', '--artnet', type=str, required=True, default="127.0.0.1", help="Art-Net server")
    parser.add_argument('-l', '--listen', type=int, required=False, default=8080, help="TCP port to listen on for web")
    parser.add_argument('-r', '--room', type=str, required=True, help="light setup for room: shop or big")
    parser.add_argument('-u', '--universe', type=int, required=False, default=1, help="Universe to send to")
    parser.add_argument('-A', '--animation', type=str, required=False, default="off", help="Initial animation")
    parser.add_argument('-C', '--color', type=str, required=False, default="255,255,0", help="Initial color")
    args = parser.parse_args(args)

    print(f"Starting DMX via Art-Net to {args.artnet}", file=sys.stderr)
    dmx = DMX(args.artnet, maxchan=128, universe=args.universe)

    if args.room == "shop":
        dmx._rgbs = [
            REDSpot18RGB(dmx, 1),
            REDSpot18RGB(dmx, 5),
            REDSpot18RGB(dmx, 9),
            REDSpot18RGB(dmx, 13),
        ]
    elif args.room == "big":
        dmx._rgbs = [
            StairvilleLedPar56(dmx, 1),
            StairvilleLedPar56(dmx, 8),
            StairvilleLedPar56(dmx, 15),
            StairvilleLedPar56(dmx, 22),
            Bar252(dmx, 29),
            Bar252(dmx, 40),
            Bar252(dmx, 51),
            Bar252(dmx, 62),
        ]
    elif args.room == "hackertours":
        dmx._rgbs = [
            ZhennbyPar(dmx, 1),
            ZhennbyPar(dmx, 8),
            ZhennbyPar(dmx, 15),
            ZhennbyPar(dmx, 22),
        ]
    else:
        print(f"Unknown room {args.room}", file=sys.stderr)
        sys.exit(64)
    room = args.room
    dmx.animation = Off()
    dmx.color = args.color.split(',')
    dmx.animation = args.animation

    run(host='0.0.0.0', port=args.listen, reloader=False, debug=True)

if __name__ == '__main__':
    main(sys.argv[1:])