#-*-coding:utf-8;-*-
#Only able to run on windows
#Can use port COM0 ~ COM9
import serial as sl
import __main__ as mn
from threading import Thread
from time import sleep
from os import getcwd as cwd

TIMEOUT = 1

class Performer(Thread):
    def __init__(this, notes, port, rtype="SR"):
        super(Performer, this).__init__()
        this.notes = notes
        this.recorder_type = rtype
        this.port = port
        this.prev = this.notes.pop()
        this.Alive = True
        this.IsPausing = False
    def run(this):
        while this.Alive:
            try:
                while this.IsPausing:
                    sleep(0.01)
                if len(this.notes) != 0:
                    note = this.notes.pop()
                    sleeplen = note.start - this.prev.end
                    sleeplen = round(sleeplen if sleeplen > 0 else 0, 3)
                    notelen = round(note.end - note.start, 3)
                    print("[pitch: {}, note:{}, sleep: {}]".format(note.pitch, notelen, sleeplen))
                    if sleeplen > 0:
                        sleep(sleeplen)
                    sendNote(this.port, note.pitch)
                    sleep(notelen)
                    sendNote(this.port)
                    this.prev = note
                else:
                    break
            except KeyboardInterrupt:
                print("ignore abortion")
        this.setAlive(False)
    def Interrupt():
        raise KeyboardInterrupt
    def setAlive(this, alive: bool):
        this.Alive = alive
    def setPausing(this, pause: bool):
        this.IsPausing = pause

def Identify():
    ret = {}
    for i in range(10):
        port = "COM" + str(i)
        try:
            tmp = sl.Serial(port, timeout=TIMEOUT)
        except sl.SerialException:
            continue
        tmp.write("ARDP:IDENTIFY\n")
        res = tmp.readline()
        if len(res) != 0:
            ret[res] = port
    if ret == {}:
        print(cwd() + "/Temp.txt")
        ret["text"] = open(cwd() + "/Temp.txt", "w+")
    return ret

def sendNote(port: sl.Serial, note=-1):
    port.write("ARDP:{}\n".format(note))
    try:
        port.flushInput()
        port.flushOutput()
    except AttributeError:
        port.flush()
