#!/usr/bin/env python3
#
# Copyright (c) 2023 Charles Godwin <magnum@godwin.ca>
#
# SPDX-License-Identifier:    BSD-3-Clause
#
# This code is provided to print a MySQL schema definition from a JSON file generate by magdump
# run the program with --help for details of options.
#  mag2sql --help
#
#  magdump|mag2sql
#  or
#  magdump|mag2sql>[filename].sql
#
import sys
import json
import argparse


def main():
    parser = argparse.ArgumentParser(description="Magnum JSON to MySQL Generator", prog="mag2sql", fromfile_prefix_chars='@',
                                     epilog="Expects input to be JSON generated by magdump. Refer to https://github.com/CharlesGodwin/pymagnum for details")
    parser.add_argument("--input", "-i", default=None,
                        help="Input file name `None` implies stdin (default: %(default)s)")
    args = parser.parse_args()
    if args.input == None:
        inputjson = sys.stdin.read()
        alldata = json.loads(inputjson)
    else:
        f = open(args.input, "r")
        alldata = json.load(f)
    db_database = alldata['device']
    print(f"create schema if not exists {db_database};")
    print(f"use {db_database};")
    for item in alldata['data']:
        table = item['device']
        print(f"create table if not exists {table} (")
        keyfield = "datetime"
        print(f"\t`{keyfield}` datetime DEFAULT now(),")
        for variable, value in item['data'].items():
            if type(value) == float:
                dbtype = "float"
            elif type(value) == int:
                dbtype = "integer"
            elif type(value) == bool:
                dbtype = "integer(1)"
            else:
                dbtype = "varchar(25)"
            print(f"\t`{variable}` {dbtype} default NULL,")
        print(
            f"\tPRIMARY KEY (`{keyfield}`)\n\t) ENGINE=InnoDB;\n")

if __name__ == '__main__':
    main()
