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

'''

Ableton Link with bridge to OSC & Redis

LICENCE : CC
Sam Neurohack

Get:

git clone --recursive https://github.com/gonzaloflirt/link-python.git

Build:

Make sure python 3 is installed on your system.

mkdir build
cd build
cmake ..
cmake --build .

'''
from libs import midix
import sys

prevphase = 0
bpm = 120

def Start():
    global lnk
    from libs import link

    print("Link ENABLED")
    lnk = link.Link(120)
    lnk.enabled = True
    lnk.startStopSyncEnabled = True
    linked = True

def RedOSC(tempo_str, beats_str):

        print()
        print("Link : BPM " +tempo_str+" Beat "+str(beats_str) + '  \r')
        #sys.stdout.flush()
        

        # redis key : "/beat" value : currentbeat
        if midix.toKey('/beat', beats_str)==True:
            pass
            #print("redis :", '/beat', beats_str)

        # OSC : /midi/cc midichannel ccnumber value
        midix.SendOSC('/beat', [beats_str])
        #print("osc :",'/beat', [beats_str])  

        # redis key : "/bpm" value : newbpm
        if midix.toKey('/bpm', bpm)==True:
            pass
            #print("redis :", '/bpm', bpm)

        # OSC : /bpm newbpm
        midix.SendOSC('/bpm', [bpm])
        #print("osc :",'/bpm', [bpm]) 


def BeatEvent():
    global lnk, prevphase


    lnkstr = lnk.captureSessionState()
    link_time = lnk.clock().micros();
    tempo_str = '{0:.2f}'.format(lnkstr.tempo())
    bpm = float(tempo_str)
    #beatstep.SendOSCUI('/bpm', [bpm])
    beats_str = '{0:.2f}'.format(lnkstr.beatAtTime(link_time, 0))
    playing_str = str(lnkstr.isPlaying()) # always False ???
    phase = lnkstr.phaseAtTime(link_time, 4)


    # new beat ?
    if int(phase) != prevphase:
        prevphase = int(phase)

        RedOSC(tempo_str, beats_str)
        currentbeat = float(beats_str)
        #midix.SendAU('/aurora/beats', beats_str)
        #AllStatus("Beat "+str(beats_str))

    # New external bpm saved in redis key ?
    redbpm = float(midix.fromKey("/bpm"))
    if bpm != redbpm:
        print("New external BPM -> Link", redbpm)
        newtempo(redbpm)


# Change current Link Tempo.
def newtempo(tempo):
    global lnk

    if linked == True:
        lnk.enabled = False
        lnk.startStopSyncEnabled = False
        lnk = link.Link(tempo)
        lnk.enabled = True
        lnk.startStopSyncEnabled = True
        bpm = tempo
        print("New BPM to Link", bpm)
        RedOSC(str(tempo), "0.0")

        ''' 
        # redis key : "/bpm" value : newbpm
        if midix.toKey('/bpm', bpm)==True:
            print("redis :", '/bpm', bpm)

        # OSC : /bpm newbpm
        midix.SendOSC('/bpm', [bpm])
        print("osc :",'/bpm', [bpm]) 
        '''

    else:
        print("Link is disabled")


# increase or decrease BPM
def BPMAdj(val1, keyname):


    # + 1
    if val1 == 1:
        newtempo(bpm+1)

    # -1
    if val1 == 127 and bpm > 0:
        newtempo(bpm-1)



