from random import choice
from time import sleep

from rv.api import Pattern, Project, m, NOTE, NOTECMD
from sunvox.api import init, Slot

"""
Explanation: Altering patterns in-place using SunVox DLL
bash
pip install radiant-voices sunvox-dll-python jupyterlab
jupyter lab
This notebook shows you how to construct a simple SunVox project using Radiant Voices, load that project into the SunVox DLL, then alter the pattern data in-place while the project is playing in a SunVox-managed thread.
Imports
End of explanation
"""


init(None, 44100, 2, 0)
slot = Slot()

"""
Explanation: Initialize SunVox
End of explanation
"""


project = Project()
inst = project.output << project.new_module(
    m.AnalogGenerator,
    sustain=False,
    release=100,
)

"""
Explanation: Create a project with an Analog Generator
End of explanation
"""


pattern = Pattern(lines=4)
project.attach_pattern(pattern)

"""
Explanation: Create a tiny 4×4 pattern
End of explanation
"""


def randomize_notes(pdata, module):
    for row in pdata:
        for note in row:
            note.module = choice([0, module.index + 1])
            note.note = NOTECMD(choice(list(NOTE))) if note.module else NOTECMD.EMPTY

randomize_notes(pattern.data, inst)
pattern.data

"""
Explanation: Randomize the notes in the pattern
End of explanation
"""


slot.load(project)
slot.play_from_beginning()

"""
Explanation: Load & play the project
End of explanation
"""


def update_pdata(pdata, pattern):
    width = len(pattern.data[0])
    for y, line in enumerate(pattern.data):
        for x, note in enumerate(line):
            pnote = pdata[y * width + x]
            pnote.note = note.note
            pnote.vel = note.vel
            pnote.module = note.module
            pnote.ctl = note.ctl
            pnote.val = note.val

pdata = slot.get_pattern_data(0)

slot.play_from_beginning()
for _ in range(25):
    randomize_notes(pattern.data, inst)
    update_pdata(pdata, pattern)
    sleep(.5)
slot.stop()

"""
Explanation: Update pattern data in place during playback
End of explanation
"""


