'''
Author: Michael Gogins

This module translates scores generated by musx (that is, MidiFile objects, or 
sequences of Seq objects) to standard Csound scores, in which each note is an 
"i" statement in the format:
```
i p1_instrument p2_time_seconds p3_duration_seconds p4_midi_key p5_midi_velocity
```
Any of these values (excepting instrument) may be a real number.
'''
import math
from .note import Note
from .seq import Seq
from musx.midi import MidiFile

'''
Translates the MIDI event into a Csound "i" statement.
'''
def to_i_statement(channel, tyme, duration, midi_key, midi_velocity):
    i_statement = "i {} {} {} {} {}".format(1 + channel, tyme, duration, midi_key, midi_velocity)
    return i_statement
    
'''
Returns a Csound score file as a single multi-line string, translated from the 
MidiFile object. It is assumed that times are in seconds. The midifile 
object could also be any Python sequence of Seq objects.
'''
def to_csound_score(midifile):
    csound_score = []
    for sequence in midifile:
        for event in sequence:
            if isinstance(event, Note) == True:
                i_statement = to_i_statement(event.instrument, event.time, event.duration, event.pitch, event.amplitude)
                csound_score.append(i_statement + "\n")
    return ''.join(csound_score)
    


