#!/usr/bin/env python
import re
import sys

infile = sys.argv[2]
with open(sys.argv[2]) as f: # TODO raise error if file cannot be opened instead of silently succeeding
    pins = []
    comp_name = ''
    comp_file = infile.split("/")[-1].split(".")[0]
    for line in f:
        comp = re.search('COMP\((\w*)\);', line)
        if comp:
            comp_name = comp.groups()[0]
        pin = re.search('HAL_PIN\((\w*)\)', line)
        if pin:
            pins.append((pin.groups()[0], int(1)))
        pin = re.search('HAL_PINA\((\w*),\s*(\d*)\)', line)
        if pin:
            pins.append((pin.groups()[0], int(pin.groups()[1])))

    header = open(sys.argv[1], 'w')
    header.write("#pragma once\n")
    header.write("//generated by " + sys.argv[0] + " DO NOT EDIT\n\n")
    header.write("#include \"hal.h\"\n")
    header.write("struct " + comp_name + "_pin_ctx_t{ // found in " + infile + "\n")
    header.write("   hal_pin_inst_t rt_prio;\n")
    header.write("   hal_pin_inst_t frt_prio;\n")
    # header.write("   hal_pin_inst_t rt_calc_time;\n")
    # header.write("   hal_pin_inst_t rt_start_time;\n")
    # header.write("   hal_pin_inst_t frt_calc_time;\n")
    # header.write("   hal_pin_inst_t frt_start_time;\n")
    # header.write("   hal_pin_inst_t nrt_calc_time;\n")
    # header.write("   hal_pin_inst_t nrt_start_time;\n")

    for (p, i) in pins:
        if i > 1:
            header.write("   hal_pin_inst_t " + p + "[" + str(i) + "]" + ";\n")
        else:
            header.write("   hal_pin_inst_t " + p + ";\n")
    header.write("};\n")
    header.close()
