from jinja2 import Template
import sys

if len(sys.argv) > 1:
    SRC_PATH = sys.argv[1]
else:
    SRC_PATH = "./"

EDIT_WARNING = """# WARNING: This file is automatically generated. 
# Update pyx_src/static.pyx and pyx_src/dynamic to change."""

ID_TYPES = [{"type_name":"ulong",
            "type_name_full":"unsigned long int",
            "type_name_short":"I"},
            {"type_name": "string",
             "type_name_full": "string",
             "type_name_short": "S"}
            ]

VALUE_TYPES = [{"type_name":"ushort",
                "type_name_full":"unsigned short int",
                "type_name_short":"US"},
                {"type_name": "uint",
                 "type_name_full": "unsigned int",
                 "type_name_short": "UI"}]


def build_param_dict(row_id_type, col_id_type, value_type):
    return_value = {}
    type_extension = '{}x{}x{}'.format(row_id_type['type_name_short'],
                                       col_id_type['type_name_short'],
                                       value_type['type_name_short'])

    return_value['class_name'] = 'transitMatrix' + type_extension
    return_value['py_class_name'] = 'pyTransitMatrix' + type_extension

    return_value['row_type'] = row_id_type['type_name']
    return_value['row_type_full'] = row_id_type['type_name_full']

    return_value['col_type'] = col_id_type['type_name']
    return_value['col_type_full'] = col_id_type['type_name_full']

    return_value['value_type'] = value_type['type_name']
    return_value['value_type_full'] = value_type['type_name_full']

    return return_value


with open(SRC_PATH + '_p2pExtension.pyx', "w+") as target:

    target.write(EDIT_WARNING)

    target.write("\n\n# Static:\n\n")

    # write static files
    with open(SRC_PATH + 'pyx_src/static.pyx') as static_file:
        static_source = static_file.read()
        target.write(static_source)

    # write dynamic files
    target.write("\n\n# Dynamic Templates: \n\n")
    with open(SRC_PATH + 'pyx_src/dynamic.pyx') as dynamic_file:
        dynamic_source = dynamic_file.read()
        dynamic_template = Template(dynamic_source)

        for row_id_type in ID_TYPES:
            for col_id_type in ID_TYPES:
                for value_type in VALUE_TYPES:
                    target.write("\n\n")
                    params = build_param_dict(row_id_type, col_id_type, value_type)
                    target.write(dynamic_template.render(**params))
