import json
from Cheetah.Template import Template
import glob
import argparse

parser = argparse.ArgumentParser(description="generate.py")
parser.add_argument('--schema', '-s',
                    help='Schema file. Default: schema.json in the current folder.',
                    required=False,
                    default='./schema.json')
parser.add_argument('--template', '-t',
                    help="""Template file, templates files must be named as the final output file
with an additional .tmpl extension. Default: all template files recursively from the current folder.""",                    
                    required=False,
                    default="**/*.tmpl")
args = parser.parse_args()


with open(args.schema) as schemaFile:
    schema = json.load(schemaFile)

for table in schema["tables"]:
    columns = table["columns"]
    for column in columns:
        if column["sqltype"] == 'serial':
            column["apitype"] = 'integer'
            column["jstype"] = 'number'
        elif column["sqltype"] == 'integer':
            column["apitype"] = 'integer'
            column["jstype"] = 'number'
        elif column["sqltype"] == 'date':
            column["apitype"] = 'string'
            column["jstype"] = 'string'
        elif column["sqltype"] == 'timestamp':
            column["apitype"] = 'string'
            column["jstype"] = 'string'
        elif column["sqltype"] == 'boolean':
            column["apitype"] = 'boolean'
            column["jstype"] = 'boolean'
        elif column["sqltype"].startswith('varchar'):
            column["apitype"] = 'string'
            column["jstype"] = 'string'
        elif column["sqltype"].startswith('numeric'):
            column["apitype"] = 'number'
            column["jstype"] = 'number'
    table["selectors"] = [ y["name"] for y in sorted([ x for x in columns if "selector" in x ], key=lambda x: x["selector"])]

schema["GENERATED_SQL_COMMENT"] = """
-- ----------------------------------------
-- THIS FILE HAS BEEN GENERATED
-- DO NOT EDIT MANUALLY
-- ----------------------------------------
"""
schema["GENERATED_PYTHON_COMMENT"] = """
# -----------------------------------------
# THIS FILE HAS BEEN GENERATED
# DO NOT EDIT MANUALLY
# -----------------------------------------
"""
schema["GENERATED_YAML_COMMENT"] = """
# -----------------------------------------
# THIS FILE HAS BEEN GENERATED
# DO NOT EDIT MANUALLY
# -----------------------------------------
"""
schema["GENERATED_TS_COMMENT"] = """
// -----------------------------------------
// THIS FILE HAS BEEN GENERATED
// DO NOT EDIT MANUALLY
// -----------------------------------------
"""

for f in glob.glob(args.template, recursive=True):
    print(f"process {f}")
    tmpl = Template(file=f, searchList=[schema])
    with open(f[:-5], 'w') as outFile:
        outFile.write(str(tmpl))