# coding=utf-8
from binascii import b2a_hex, a2b_hex

from adapters.acrel_dtsy1352 import AcrelDTSY1352
from adapters.acrel_adw300 import AcrelADW300
from adapters.acrel_dtsy1352_4g import AcrelDTSY13524G


def dispatch(data, protocol, logger):
    factory = protocol.factory
    adapter_type = factory.adapter_type[protocol.clientID]
    if adapter_type == '':
        '''parse adapter header type'''
        header = b2a_hex(data[:2]).decode()

        if header.lower() == "1f1f":
            adapter_type = "ACREL-ANet"
        elif header.lower() == "7b7b":
            meter_id = a2b_hex((b2a_hex(data).decode())[6:46]).decode().replace("\x00", "")
            if meter_id[6:8] == "01":
                adapter_type = "ACREL-ADW300"
            elif meter_id[6:8] == "02":
                adapter_type = "ACREL-DTSY1352-4G"
            elif meter_id[6:8] == "03":
                adapter_type = "ACREL-DDSY1352-4G"
            elif meter_id[6:8] == "00":
                adapter_type = "ACREL-ADW300"
            else:
                adapter_type = "UNDEFINED"
        else:
            adapter_type = "UNDEFINED"
        logger.debug("协议类型：{}".format(adapter_type))
        factory.adapter_type.update({protocol.clientID: adapter_type})

    adapter_class = get_adapter_class(adapter_type)
    return adapter_class


def get_adapter_class(class_type):
    if class_type == "ACREL-ANet":
        return AcrelDTSY1352()
    elif class_type == "ACREL-ADW300":
        return AcrelADW300()
    elif class_type == "ACREL-DTSY1352-4G":
        return AcrelDTSY13524G()
    elif class_type == "ACREL-DDSY1352-4G":
        return AcrelDTSY13524G()
    else:
        return

