#!/usr/bin/env python3
#
#@file mrt-ble
#@brief python script to generate code for gatt profile
#@author Jason Berger
#@date 03/20/2020
#

import sys
import os
from mako.template import Template
import yaml
import json
import argparse
import pkgutil
from mrtutils.mrtTemplateHelper import *
from mrtutils.gatt_profile import GattProfile
from mrtutils.updates import *


# Initialize the argument parser
def init_args():
    global parser
    parser = argparse.ArgumentParser("Tool to generate code for ble profile")
    parser.add_argument('-i', '--input', type=str, help='input file to parse', default="")
    parser.add_argument('-o', '--output', type=str, help='Output path', default=".")
    parser.add_argument('-d', '--document', type=str, help='documentation path', default="")
    parser.add_argument('-t', '--template', type=str, help='path to create template', default="")
    parser.add_argument('-n', '--nrf', action='store_true', help='Generates definition file for nrf connect', default=False)
    

def buildTemplate(object, templateFile, outputFile):
    exists= False
    cr = CodeReplacer()
    newContents =""
    headerPattern = r"@file (.*?\.)(.*?) \*/"
    handlerPattern = r" (.*?)_handler.*?\n}"
    if os.path.isfile(outputFile):
        exists = True
        curFile = open(outputFile, "r")
        text = curFile.read()
        cr.loadText(text)
        cr.loadText(text,headerPattern)
        cr.loadText(text,handlerPattern)

    template = Template(pkgutil.get_data('mrtutils',templateFile) )
    newContents = "\n".join(template.render(obj = object, t = TemplateHelper()).splitlines())
    newContents = cr.insertBlocks(newContents)
    newContents = cr.insertBlocks(newContents,headerPattern)
    newContents = cr.insertBlocks(newContents,handlerPattern)
    cr.printDrops()
    text_file = open( outputFile , "w")
    text_file.write(newContents)
    text_file.close()

def buildProfileSource(gatt , outputPath, baseName =''):

    if baseName == '':
        baseName = gatt.name.lower() 
    
    if not os.path.exists(outputPath):
        os.makedirs(outputPath)
    
    if not os.path.exists(outputPath +"/svc"):
        os.makedirs(outputPath+"/svc")

    buildTemplate(gatt, 'templates/ble/profile_header.h', outputPath +"/"+gatt.name.lower() + "_profile.h" )
    buildTemplate(gatt, 'templates/ble/profile_source.c', outputPath +"/"+gatt.name.lower() + "_profile.c" )

    for service in gatt.services:
        buildTemplate(service, 'templates/ble/service_header.h', outputPath +"/svc/"+service.prefix + "_svc.h" )
        buildTemplate(service, 'templates/ble/service_source.c', outputPath +"/svc/"+service.prefix + "_svc.c" )
        buildTemplate(service, 'templates/ble/app_service_source.c', outputPath +"/app_" + service.prefix+"_svc.c" )



def main():
    global path
    global parser
    global args

    updateCheck()

    init_args()
    args= parser.parse_args()
    argCount = len(sys.argv)
    

    inputFile = args.input
    path = args.output
    docPath = args.document
    templatePath = args.template

    gatt = GattProfile()

    if not templatePath =="":
        templatePath.replace("yml","") 
        contents = pkgutil.get_data('mrtutils','templates/ble/gatt_descriptor_template.yml')
        text_file = open( templatePath + '.yml' , "w")
        text_file.write(contents.decode("utf-8"))
        text_file.close()
        sys.exit()


    if inputFile == "":
        print("No input file specified, use -t to create a template file")
        sys.exit()

    if os.path.isfile(inputFile):


        # if os.path.isfile(inputFile):
        print("parsing " + inputFile )
        gatt.parseYaml(inputFile)
        gatt.hash = 'na'
        

        print(" Generating Documentation and source for " + gatt.name)
        
        buildProfileSource(gatt, path)

   
        gatt.json = json.dumps(gatt.getDict(), indent=2)
        #print(s)

        if args.nrf:
            buildTemplate(gatt, 'templates/ble/nrf_definitions.json', path +"/" + gatt.name+"_definitions.json" )


        if not docPath == "":
            buildTemplate(gatt, 'templates/ble/gatt_icd.html', docPath +"/" + gatt.name+"_gatt_icd.html" )
            buildTemplate(gatt, 'templates/ble/smart_icd.html', docPath +"/" + gatt.name+"_live_icd.html" )
        


if __name__ == "__main__":
    main()