#! /usr/bin/env python3

from tones import SINE_WAVE, SAWTOOTH_WAVE, SQUARE_WAVE
from tones.mixer import Mixer
import csv
import sys

GROUP_DURATION = 1.0
SILENCE_DURATION = 0.2
CHANNELS = 2

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

code = sys.argv[1]
print(f"Generating tone for SELCAL {code}")

# Create mixer, set sample rate and amplitude
mixer = Mixer(44100, 1)
for i in range(CHANNELS):
    mixer.create_track(i, SQUARE_WAVE)

groups = code.split("-")
for groupindex,group in enumerate(groups):
    for channel,tone in enumerate(group):
        mixer.add_tone(channel, frequency=tones[tone], duration=GROUP_DURATION)

    if groupindex != len(groups) - 1:
        for i in range(CHANNELS):
            mixer.add_silence(i, duration=SILENCE_DURATION)

# Mix all tracks into a single list of samples and write to .wav file
mixer.write_wav(f'{code}.wav')
