#!/usr/bin/env python3
#coding:utf-8

'''
使用说明：
1、从DP平台下载Product_<pid>.json和Profile_<pid>.json这两个文件，放到本python文件的目录下。
2、运行脚本python3 ohos_yat_config.py
3、程序会列出当前目录下所有的pid，用户选择需要生成配置文件的pid，然后输入波特率、TLV/Json格式，然后程序就会自动在本目录下生成Config_<pid>.bin的文件，这个文件就是yat的配置文件。
'''

import os
import json

def profile_parse(filename):
    with open(filename, 'r', encoding='utf-8') as profile_file:
        profile = json.load(profile_file)
    outDict = {"profile": []}
    tag = 1
    j = 0
    for service in profile['services']:
        if (service['serviceType'] == 'ota'):
            continue
        if (service['serviceType'] == 'netInfo'):
            continue
    
        profileDict = {"tag": 0,
                    "identifier": "",
                    "ServiceType": "",
                    "dataType": "struct",
                    "struct": []}
        profileDict['tag'] = tag
        tag += 1
        profileDict['identifier'] = service['serviceId'] 
        profileDict['ServiceType'] = service['serviceType'] 
        outDict["profile"].append(profileDict)

        for character in service['characteristics']:
            structDict = {"tag": 1,
                        "identifier": "",
                        "dataType": "enum",
                        "permissions": {"PUT": 1, "GET": 1, "REPORT": 1}}
            structDict['tag'] = tag
            tag+=1
            structDict['identifier'] = character['characteristicName']
            structDict['dataType'] = character['characteristicType']
            structDict['permissions']["PUT"] = 1 if "P" in character['permission'] else 0
            structDict['permissions']["GET"] = 1 if "G" in character['permission'] else 0
            structDict['permissions']["REPORT"] = 1 if "R" in character['permission'] else 0
            outDict["profile"][j]["struct"].append(structDict)
        j += 1

    #print(outDict)
    return outDict


if __name__ == "__main__":
    f_list = os.listdir(os.getcwd())
    
    while True:
        index=0
        pid_list=[]
        filelist=""
        for i in f_list:
            # os.path.splitext():????????????????
            if os.path.splitext(i)[1]  == '.json':
                if i.startswith('Product_'):
                    pid_list.append(i[8:12])
                    if (index == 0):
                        filelist += str(index) + ":" + i[8:12] + "(default) "
                    else:
                        filelist += str(index) + ":" + i[8:12] + " "
                    index = index + 1

        inputstr = "Choose product[" + filelist + "]: "
        num = int(input(inputstr) or "0")
        product="Product_" + pid_list[num] + '.json'
        profile="Profile_" + pid_list[num] + '.json'
        if (not os.path.exists(product)):
            print(product + ' is not exist!')
            continue 
        if (not os.path.exists(profile)):
            print(profile + ' is not exist!')
            continue
        break

    print("PID is: " + pid_list[num])

    baud=int(input("Please input yat baudrate(default 115200):") or "115200")
    print("Baudrate is: %d" %baud)
    mode=int(input("Choose yat mode[0=JSON,1=TLV(default)]:") or "1")
    while (mode!=0 and mode!=1): 
        print("Please input 0 or 1")
        mode=int(input("Please input yat mode(0=JSON,1=TLV):"))

    if (mode==0):
        print("YAT mode is JSON")
    else:
        print("YAT mode is TLV")

    hilink_get=int(input("Input hilink get wait time(ms):") or "500")
    print("hilink get wait %d ms" %hilink_get)
        
    with open(product, 'r', encoding='utf-8') as product_file:
        product_j = json.load(product_file)

    hilinkpackage = {}
    totalpackage = {}
    configpackage = {}
    configpackage["product_id"] = product_j["prodId"]
    configpackage["product_key"] = product_j['prodKey']
    configpackage["product_series"] = product_j['productSeries']
    configpackage["device_type"] = product_j['deviceTypeId']
    configpackage["device_model"] = product_j['deviceModel']
    configpackage["manuafacturer"] = product_j['manufacturerId']
    configpackage["device_type_name"] = product_j['deviceTypeNameEn']
    configpackage["manuafacturer_name"] = product_j['manufacturerNameEn']
    configpackage["ac"] = product_j['acKey']
    configpackage["bi"] = ""
    configpackage["brand"] = product_j['brandEn']
    configpackage["hw_ver"] = product_j['hardwareVer']
    if (configpackage["hw_ver"]==None):
        configpackage["hw_ver"] = ''

    totalpackage["ver"] = "1.0.0"   
    totalpackage["baud"] = baud
    totalpackage["mode"] = mode
    totalpackage["get_timeout"] = hilink_get
    totalpackage["configType"] = 1
    totalpackage["nan"] = 1
    totalpackage["distancePwr"] = 1
    totalpackage["surfacePwr"] = 1

    totalpackage["config"] = configpackage

    profile_j = profile_parse(profile)
    totalpackage.update(profile_j)
    hilinkpackage["hilink"] = totalpackage
    hilinkJSON = json.dumps(hilinkpackage).replace(' ','')

    # print(json.dumps(hilinkpackage, indent=2))
    hilinkJSONlen = len(hilinkJSON) + 4
    # print(">>>>>>len:", hilinkJSON)
    inputpayload = hilinkJSONlen.to_bytes(4, 'little') + hilinkJSON.encode()

    configfile = 'Config_' + pid_list[num] + '.bin'
    with open(configfile, 'wb') as ConfFile:
        ConfFile.write(inputpayload)
        print("The configure file is: "+ configfile)