# nbi:hide_in
import pickle
from ipywidgets import interact
import numpy as np
from music21 import *
    
harmonies_to_melodies = pickle.load(open("widgets/CTM.pkl", "rb"))

def chord_to_melody(c):
    if c in harmonies_to_melodies.keys():
        possible_melodies = harmonies_to_melodies[c]
        if len(list(possible_melodies)) == 1:
            return list(possible_melodies)[0]
        else:
            return np.random.choice(list(possible_melodies))
    else:
        return -1
    
def add_melody_to_list(part, melody):
    for n in melody:
        if n > 0:
            part.append(note.Note(pitch.Pitch(n)))
        else:
            part.append(note.Rest(-n))
    return part

# nbi:hide_in
def getChordAndMelody(random_seed):
    np.random.seed(random_seed)
    c = np.random.choice(list(harmonies_to_melodies.keys()))
    melody = chord_to_melody(c)
    lst = []
    lst = add_melody_to_list(lst, melody)
    print("Chord: ", chord.Chord(c).pitchedCommonName)
    print("Melody: ", lst)

interact(getChordAndMelody, random_seed=(0,100));
# nbi:hide_in