#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2021, Nils Hilbricht, Germany ( https://www.hilbricht.net )

This file is part of the Laborejo Software Suite ( https://www.laborejo.org ),

This application is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

"""
A helper module to quickly generate some cbox patterns and notes with lilypond and simple functions.
This is mostly meant for development and testing.
"""

#Standard Library Modules
import re

#Third Party Modules
from calfbox import cbox

#Template Modules
from . import pitch
from .duration import DB, DL, D1, D2, D4, D8, D16, D32, D64, D128


lyToMidi = {} #filled for all pitches on startup, below
for ly, _pitch in pitch.ly2pitch.items():
    octOffset = (pitch.octave(_pitch) +1) * 12 #twelve tones per midi octave
    lyToMidi[ly] = octOffset +  pitch.halfToneDistanceFromC(_pitch)


lyToTicks = {
    "16" : D16,
     "8" : D8,
     "4" : D4,
     "2" : D2,
     "1" : D1,
    }

def ly(lilypondString:str):
    """Take string of simple lilypond notes, return midi pitches as generator of (pitch, ticks)"""
    lastDur = "4"
    for lyNote in lilypondString.split(" "):
        try:
            lyPitch, lyDur = re.split(r'(\d+)', lyNote)[0:2]
            lastDur = lyDur
        except ValueError:
            lyPitch = re.split(r'(\d+)', lyNote)[0]
            lyDur = lastDur

        yield (lyToMidi[lyPitch], lyToTicks[lyDur])


def pattern(lilypondString:str, channel, velocity:int=100):
    #Return (pbytes, durationInTicks)
    """
    Return a cbox pattern
    a python byte data type with midi data for cbox.
    
    Channel is 1-16."""
    #cbox.Pattern.serialize_event(position, midibyte1 (noteon), midibyte2(pitch), midibyte3(velocity))
    channel -= 1
    patternBlob = bytes()
    tickCounter = 0
    for midiPitch, durationInTicks in ly(lilypondString):
        endTick = tickCounter + durationInTicks - 1  #-1 ticks to create a small logical gap. This is nothing compared to our tick value dimensions, but it is enough for the midi protocol to treat two notes as separate ones. Imporant to say that this does NOT affect the next note on. This will be mathematically correct anyway.
        patternBlob += cbox.Pattern.serialize_event(tickCounter, 0x90+channel, midiPitch, velocity) # note on
        patternBlob += cbox.Pattern.serialize_event(endTick, 0x80+channel, midiPitch, velocity) # note off
        tickCounter = tickCounter + durationInTicks #no -1 for the next note
    
    pattern = cbox.Document.get_song().pattern_from_blob(patternBlob, tickCounter)
    #return patternBlob, startTick
    return pattern

