'''
This program converts a .msync file into a corresponding Arduino .h file
'''

import csv
import os
import argparse

from utils import create_unique_filename

''' Constants '''
TIMESTAMP_ARRAY_PREFIX = 'const long TIMESTAMPS[] PROGMEM = { '
LEFT_PANS_ARRAY_PREFIX = 'const int LEFT_PANS[] PROGMEM = { '
LEFT_TILTS_ARRAY_PREFIX = 'const int LEFT_TILTS[] PROGMEM = { '
RIGHT_PANS_ARRAY_PREFIX = 'const int RIGHT_PANS[] PROGMEM = { '
RIGHT_TILTS_ARRAY_PREFIX = 'const int RIGHT_TILTS[] PROGMEM = { '

ap = argparse.ArgumentParser(
    description="Convert a .msync file to constant arrays for Arduino processing")
ap.add_argument('input', help="The input .msync file to process")
ap.add_argument('-o', '--output', help="The output .h file to write to")

args = ap.parse_args()

msync_file = args.input

output_filename = None
if args.output is None:
    output_filename = create_unique_filename(
        f"outputs/ArduinoExporter/{os.path.splitext(os.path.basename(msync_file))[0]}.h")
else:
    output_filename = args.output


def parse_row(row):
    return str(round(float(row['timestamp']))), str(round(float(row['left_pan']))), str(round(float(row['left_tilt']))), str(round(float(row['right_pan']))), str(round(float(row['right_tilt'])))

def main():
    with open(msync_file) as input_file:
        msync_reader = csv.DictReader(input_file)

        timestamps, left_pans, left_tilts, right_pans, right_tilts  = zip(*[parse_row(r) for r in msync_reader])
        
        timestampsArray = TIMESTAMP_ARRAY_PREFIX + "L, ".join(timestamps[::2]) + "L };"
        
        leftPansArray = LEFT_PANS_ARRAY_PREFIX + ", ".join(left_pans[::2]) + " };"
        leftTiltsArray = LEFT_TILTS_ARRAY_PREFIX + ", ".join(left_tilts[::2]) + " };"
        rightPansArray = RIGHT_PANS_ARRAY_PREFIX + ", ".join(right_pans[::2]) + " };"
        rightTiltsArray = RIGHT_TILTS_ARRAY_PREFIX + ", ".join(right_tilts[::2]) + " };"
        
        with open(output_filename, "w+") as output_file:
            print("// Arrays auto-generated by ArduinoExporter.py", file=output_file)
            print(timestampsArray, file=output_file)
            print(leftPansArray, file=output_file)
            print(leftTiltsArray, file=output_file)
            print(rightPansArray, file=output_file)
            print(rightTiltsArray, file=output_file)

    print(f"Arduino code exported to: {output_filename}")


if __name__ == '__main__':
    main()
