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

comps = []

code = open(sys.argv[1], 'w')

for infile in sys.argv[2:]:
    with open(infile) as f:
        pins = []
        compname = ''
        comp_file = infile.split("/")[-1].split(".")[0]
        for line in f:
            comp = re.search('COMP\((\w*)\);', line)
            if comp:
                compname = 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])))
        comps.append((compname, pins, infile, comp_file))

code.write("#include \"hal.h\"\n\n")
code.write("//generated by " + sys.argv[0] + " DO NOT EDIT\n\n")
for comp_name, pins, file_name, comp_file in comps:
    code.write("extern const hal_comp_t " + comp_name + "_comp_struct; // found in " + file_name + "\n")
code.write("\n\n")
code.write("const hal_comp_t * comps[] = {\n")
for comp_name, pins, file_name, comp_file in comps:
   code.write("   &" + comp_name + "_comp_struct, // found in " + file_name + "\n")
code.write("};\n\n")
code.write("const uint32_t comp_count = sizeof(comps) / sizeof(comps[0]);\n\n")

code.write("const pin_t pins[] = {\n")
for comp_name, pins, file_name, comp_file in comps:
    code.write("   // pins for comp " + comp_name + " found in " + file_name + "\n")
    code.write("   \"rt_prio\",\n")
    code.write("   \"frt_prio\",\n")
    # code.write("   \"rt_calc_time\",\n")
    # code.write("   \"rt_start_time\",\n")
    # code.write("   \"frt_calc_time\",\n")
    # code.write("   \"frt_start_time\",\n")
    # code.write("   \"nrt_calc_time\",\n")
    # code.write("   \"nrt_start_time\",\n")
    
    for (p, i) in pins:
        if i > 1:
            for j in range(i):
                code.write("   \"" + p + str(j) + "\",\n")
        else:
            code.write("   \"" + p + "\",\n")

code.write("};\n\n")
code.write("const uint32_t pin_count = sizeof(pins) / sizeof(pins[0]);\n\n")

# header.close()
code.close()
