import paho.mqtt.client as mqtt
from blinkenbase.animation_handler import AnimationHandler

handler = AnimationHandler()

command_handler_dict = {}

client = mqtt.Client()

def on_connect(c, u, f, rc):
    print("connected")
    client.subscribe("light/blinkenfoo")

def on_message(client, userdata, p_message):
    p_message = p_message.payload.decode("UTF-8")
    print("Received message:", p_message)
    args = p_message.split(" ")
    if args[0] in command_handler_dict:
        command_handler = command_handler_dict[args[0]]
        command_handler(args[1:])

client.on_connect = on_connect
client.on_message = on_message

def handler_start_animation(p_args):
    if len(p_args) > 1 and len(p_args) % 2 == 0:
        print("Animation args count invalid")
        return

    animation_name = p_args[0]
    animation_args_dict = {}
    for i in range(1, len(p_args), 2):
        key = str(p_args[i])
        value = p_args[i+1]
        animation_args_dict[key] = value

    handler.start_animation(animation_name, animation_args_dict)

def handler_pause(p_args):
    length = len(p_args)
    if length is 0:
        handler.pause_all_animations()
    else:
        args = p_args[1:]
        for name in args:
            handler.pause_animation(name)

def handler_resume(p_args):
    length = len(p_args)
    if length is 0:
        handler.resume_all_animations()
    else:
        args = p_args[1:]
        for name in args:
            handler.resume_animation(name)

command_handler_dict["play"] = handler_start_animation
command_handler_dict["exit"] = handler.stop_all_animations
command_handler_dict["resume"] = handler_resume
command_handler_dict["pause"] = handler_pause
command_handler_dict["darken"] = handler.darken
command_handler_dict["lighten"] = handler.lighten

client.connect("warpsrvint.warpzone", 1883, 60)
client.loop_forever()