import re
import time

print('{\n    "VERSION":' + str(int(time.time())) + ',')
print('    "COMMENT":"Do not edit this file directly it is generated.",')
print('    "PRODUCTS":[')

#
# output the known products captured by GoldenCheetah users
#
nongarmin = open("nongarmin.json", "r")
lines = nongarmin.readlines()
for line in lines:
    print("        " + line, end="")

#
# output garmin products as described in the FIT SDK
#
sdkheader = open("fit_example.h","r")
lines = sdkheader.readlines()
pre="        "
for line in lines:
    match = re.search("FIT_GARMIN_PROD", line)
    if match:
        name = re.search("(FIT_GARMIN_PRODUCT_)([^ \t]*)", line)
        id = re.search("\(FIT_GARMIN_PRODUCT, ([ 0-9]*)", line)
        if name and id:
            # extract name
            print(pre+ '{ "manu":1, "prod":' + id.group(1).strip() + ', "name":"' +  name.group(2).strip().replace('_',' ').title() + '" }', end="")
            pre=",\n        "
print("\n    ],\n")

#
# manufacturers list from FIT SDK
#
print('    "MANUFACTURERS":[')
pre="        "
for line in lines:
    match = re.search("MANUFACTURER_([^ \t]*).*\(FIT_MANUFACTURER, ([ 0-9]*)", line)
    if match:
        print(pre+ '{ "manu":' + match.group(2).strip() + ', "name":"' +  match.group(1).strip().replace('_',' ').title() + '" }', end="")
        pre=",\n        "

print("\n    ],\n")

#
# field numbers
#
fields = open("fields.json", "r")
fieldlines = fields.readlines()
for line in fieldlines:
    print(line, end="")

#
# Message number description
#
# // #define FIT_MESG_NUM_HR_ZONE                                                     (FIT_CAST(FIT_MESG_NUM, 8))

print('    "MESSAGES":[')
pre="        "
for line in lines:
    match = re.search("FIT_MESG_NUM_([^ \t]*).*\(FIT_MESG_NUM, ([ 0-9]*)", line)
    if match:
        num = int(match.group(2).strip())
        if num > 0:
            print(pre+ '{ "num":', num, ', "desc":"' +  match.group(1).strip().replace('_',' ').title() + '" }', end="")
            pre=",\n        "

print("\n    ]\n}")
