#!/usr/bin/env python3

"""
Create sets of C++ header config based on provided device
"""

import argparse
import os
import sys


# consts
IsPython3 = ( sys.version_info[0] >= 3 )


# Templates

device_setup_header_template = """
/*******************************************************************************
This file is part of the pdi stack.

This is free software. you can redistribute it and/or modify it but without any
warranty.

File            : DeviceSetup.h
Author          : Suraj I.
created Date    : 1st Jan 2025

Note            : THIS FILE IS AUTOGENERATED - DO NOT EDIT MANUALLY
*******************************************************************************/


/**
 * enable configuration for the below device
 */

#define %DEVICE%

"""

import Util

def generate_setup_header(device, outpath):

    print("Generating DeviceSetup.h file for device %s" % device)

    # Prepare device include macro
    template = Util.clean_template(device_setup_header_template)
    template = Util.expand_token(template, '%DEVICE%', Util.get_device_id(device))
    template = Util.clean_template(template, True)

    # Build output file path
    outfilepath = os.path.abspath(os.path.expanduser(outpath))
    if os.path.isdir(outfilepath) or outfilepath.endswith(os.sep):
        outfilepath = os.path.join(outfilepath, "DeviceSetup.h")
    else:
        outfilepath = os.path.join(outfilepath + os.sep, "DeviceSetup.h")
    
    # Write to output file
    with open(outfilepath, mode="w", encoding="ascii", newline=os.linesep) as file:
        file.write(template) 
    
    # Format the generated file with clang-formatter
    Util.format_file("clang", outfilepath)

def create_db_source(device):

    # Build schema file path
    devicerootpath = Util.get_device_folder_relpath(device)
    if os.path.exists(devicerootpath):
        schemafile = devicerootpath + "/config/DBTableSchema.json"
        if os.path.exists(schemafile):
            print("Generating DB table files for device %s" % device)
            os.system('python3 CreateDBSourceFromJson.py --schema ' + schemafile)
        else:
            print("No schema file found for device %s" % device)
    else:
        print("No device folder found for device %s" % device)



if __name__ == "__main__":

    usage = """
        DeiceSetup [--device|-d device]
    """

    parser = argparse.ArgumentParser(usage=usage)
    parser.add_argument(
                        '--device', '-d', 
                        help='device to setup', 
                        required=True
                        )

    args = parser.parse_args()

    try:

        generate_setup_header(args.device, "../devices/")
        create_db_source(args.device)

    except Exception as ex:
        print("Exception : %s" %ex)

    except KeyboardInterrupt:
        print("Aborted by keyboard interrupt !")