#! /usr/bin/env python3

from tones import SQUARE_WAVE, SINE_WAVE
from tones.mixer import Mixer
import csv
import math

def frequency_to_midi(frequency):
    '''
    There are only 128 midi notes. The don't map nicely
    to the SELCAL frequencies :'(

    MIDI note #69 is A4 @ 440 Hz. The other notes are given by:
    f = 440 * 2 ^ (n - 69)/12
    '''
    note = 12 * (math.log(frequency/220)/math.log(2)) + 57
    #return round(note)
    return note

tones = {}
with open('tones.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        tones[row['designator']] = float(row['frequency'])

for tone in tones:
    print(f"{tone} is MIDI #{frequency_to_midi(tones[tone])}")

    mixer = Mixer(44100, 1)
    mixer.create_track(0, SINE_WAVE)
    mixer.add_tone(0, frequency=tones[tone], duration=1.0)
    mixer.write_wav(f'samples/{tone}.wav')


mixer = Mixer(44100, 1)
mixer.create_track(0, SQUARE_WAVE)
mixer.add_tone(0, frequency=440, duration=1.0)
mixer.write_wav(f'samples/MIDI-69-square.wav')

mixer = Mixer(44100, 1)
mixer.create_track(0, SINE_WAVE)
mixer.add_tone(0, frequency=440, duration=1.0)
mixer.write_wav(f'samples/MIDI-69-sine.wav')

mixer = Mixer(44100, 1)
mixer.create_track(0, SQUARE_WAVE)
mixer.add_tone(0, frequency=261.6256, duration=1.0)
mixer.write_wav(f'samples/MIDI-60-square.wav')

mixer = Mixer(44100, 1)
mixer.create_track(0, SINE_WAVE)
mixer.add_tone(0, frequency=261.6256, duration=1.0)
mixer.write_wav(f'samples/MIDI-60-sine.wav')