import json
from .auto_generate_python import TDSCmd_pb2, OAM_datastruct_pb2, Device_datastruct_pb2
from .auto_generate_python.Device_datastruct_pb2 import TDSXDC_Device_cmd
from google.protobuf.json_format import MessageToJson


def parse_proto(data: bytes) -> (dict, str):
    """
    解析发送过来的 protobuf
    :param data: protobuf 的二进制流
    :return:
        dict: 解析完成的 protobuf
        str: 设备名
    """
    cmd = TDSCmd_pb2.TDSCmd()
    cmd.ParseFromString(data)

    device_cmd = TDSXDC_Device_cmd()
    cmd.parameters[0].Unpack(device_cmd)

    # data = MessageToJson(device_cmd,
    #                      including_default_value_fields=True,
    #                      preserving_proto_field_name=True)

    # device_cmd_dict = json.loads(data)
    # print(device_cmd_dict)
    data = {item.fieldName: item.value
            for item in device_cmd.fields}
    # return json.dumps(json.loads(data), separators=(',', ':'))
    return data, device_cmd.dev_name


def compose_protobuf_message(param: dict, dst_suid: int) -> bytes:
    cmd = TDSCmd_pb2.TDSCmd()
    cmd.interface_id = TDSCmd_pb2.IID_Device_Xpro_TX_cmd
    cmd.dst_suid = dst_suid
    cmd.src_suid = 0x1116_0000
    cmd.priority = 100
    cmd.ts.GetCurrentTime()

    parameters = TDSXDC_Device_cmd()
    parameters.DeviceID = param['device_id']
    parameters.cmd_name = param['cmd_name']

    for param_field in param['fields']:
        field = parameters.fields.add()
        field.fieldName = param_field['fieldname']
        field.value = param_field['value']
    
    cmd.parameters.add().Pack(parameters)
    data = cmd.SerializeToString()
    return data
