#!/usr/bin/python3

import argparse
import re
import redis
import runner_lib as runner
import time

novationRows = [
  [ 0, 1, 2, 3, 4, 5, 6, 7 ],
  [ *range(16,24)],
  [ *range(32,40)],
  [ *range(48,56)]
]

argsparser = argparse.ArgumentParser(description="Playlist midi")
argsparser.add_argument("playlist",help="JSON playlist file ",type=str)
argsparser.add_argument("-i","--ip",help="IP address of the Redis server ",default="127.0.0.1",type=str)
argsparser.add_argument("-r","--row",help="Row of Novation pad. Default:1 ",default=1,type=str)
argsparser.add_argument("-k","--key",help="Redis key to update",default="0",type=str)
argsparser.add_argument("-l","--laser",help="Laser number. Default:0 ",default=0,type=int)
argsparser.add_argument("-p","--port",help="Port of the Redis server ",default="6379",type=str)
argsparser.add_argument("-s","--scene",help="Laser scene. Default:0 ",default=0,type=int)
argsparser.add_argument("-v","--verbose",action="store_true",help="Verbose")
args = argsparser.parse_args()

ip = args.ip
port = args.port
key = args.key
verbose=args.verbose
laser = args.laser
scene = args.scene
playlist = args.playlist
row = args.row - 1
rowKeys = novationRows[row]



# Subscriber

r = redis.StrictRedis(host=ip, port=port, db=0)
p = r.pubsub()
p.subscribe('/midi/last_event')
runner._killBill()

# Set Laser and scene
runner._setKey( laser = laser, scene = scene)

# Load playlist
runner._loadPlaylist( playlist )

print("Loaded playlist : {}".format(runner.currentPlayList))


runner.action_info()
runner.current_id = -1 
while True:
  runner._killBill()

  message = p.get_message()
  if message:
    #runner._ok ("Subscriber: %s" % message['data'])

    
    # b'/midi/noteon/0/19/127'
    match   = re.match(".*/([0-9]+)/[0-9]+",str(message['data']))
    if not match: 
      continue
    key     = int(match.group(1))

    # Check if the event is for us 
    if key not in rowKeys:
      print("key {} not in {} ".format(key,rowKeys))
      continue

    try:
      command_id = rowKeys.index(key)
      cmd = runner.currentPlayList[command_id]

      if command_id != runner.current_id :
        runner._ok("Launching command #{}\n  Previous was {}\n  Cmd:{}".format(command_id,runner.current_id,cmd))
        runner.action_match(command_id)   
        runner.action_runCommand()
      else :
        runner._err("Not running {} : already running.".format(command_id))
    except Exception as e :
      print("Woops.",e)
