#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
miredis
v0.1

Forward midi events to a redis.

# CC rotary -> midi CC.         

cross        49
joystick UD  57
joystick LR  56

LEFT:

menu        7
play/pause  8
cue         9

beat        10

pitch +     19
pitch -     20
jog         54
headset     21
volume      50
load deck   27
beatlck     22
1           15
2           14
3           13
bass        46
medium      47
trebble     48
track -     11
track +     12


RIGHT:

menu        1
play/pause  2
cue         3

beat        4

pitch +     23
pitch -     24
jog         55
headset     25
volume      51
load deck   28 
beatlck     26
1           16
2           17
3           18
bass        43
medium      44
treblle     45
track -     5
track +     6

by Sam Neurohack 
from /team/laser

"""
from libs import log

print()
log.infog('Miredis v0.1')

import argparse
import redis
from libs import midix
import traceback


#myHostName = socket.gethostname()
#print("Name of the localhost is {}".format(myHostName))
#gstt.myIP = socket.gethostbyname(myHostName)
#print("IP address of the localhost is {}".format(gstt.myIP))

#gstt.myIP = "127.0.0.1"
#print('Used IP', gstt.myIP)



argsparser = argparse.ArgumentParser(description="Miredis")
# General Args
argsparser.add_argument("-v","--verbose",action="store_true",help="Verbose")
# Redis Args
argsparser.add_argument("-i","--ip",help="IP address of the Redis server ",default="127.0.0.1",type=str)
argsparser.add_argument("-p","--port",help="Port of the Redis server ",default="6379",type=str)
# OSC Args
argsparser.add_argument("-o","--oscip",help="IP address of the OSC server to forward midi events.",default="127.0.0.1",type=str)
argsparser.add_argument("-q","--oscport",help="Port of the OSC server ",default="9000",type=str)
argsparser.add_argument('-link',help="Enable Ableton Link (disabled by default)", dest='link', action='store_true')
argsparser.set_defaults(link=False)

args          = argsparser.parse_args()
redisIP       = args.ip
redisPORT     = args.port
midix.oscIP   = args.oscip
midix.oscPORT = int(args.oscport)
midix.debug   = args.verbose

# with Ableton Link
if args.link  == True:
    from libs import alink

    alink.Start()
    linked = True
else:
    print("Link DISABLED")
    linked = False

r = redis.StrictRedis(host=redisIP , port=redisPORT, db=0)
midix.r = r




def Osc():

    p = r.pubsub()
    p.subscribe('updates')
    print("Artnet updates subscribed")
    
    while True:

        # Handle OSC based changed
        OSCframe()

        # Handle Artnet change via redis key 'updates' subscription
        message = p.get_message()
        
        if message:
            messageCC = message['data']
            # print(type(messageCC))
            #print("Updates said: %s" % messageCC)
            if messageCC != 1:
                #if ":" in str(messageCC.decode('utf_8')):
                messageCC = messageCC.decode('utf_8')
                artnetCC = messageCC.split(":")               
                if len(artnetCC) > 1:
                    cc(int(artnetCC[0]), round(int(artnetCC[1])/2))
                    print()

        #time.sleep(0.0)





if __name__ == '__main__':


    import traceback
    import time

    midix.check()

    midix.toKey("/beats","0.0") 
    midix.toKey("/bpm",120)

    try:

        while True:
            time.sleep(0.001)
            if linked:
                alink.BeatEvent()

    except Exception:
        traceback.print_exc()

    #finally:

