import time
import json
from datetime import datetime
def bcc(msg):
    numb = len(msg)
    nb = int(numb / 2)
    bcc = 0
    for i in range(nb):
        a = 2 * i
        b = 2 * (i + 1)
        aa = msg[a:b]
        bcc = bcc ^ int(aa, 16)
    return bytes.fromhex(f'{bcc:x}'.zfill(2))

def split(buf):
    def find_end(buf,s):
        e = bytes(buf[s+1:]).find(b'\xff')
        if e == -1:
            return e
        return e + s + 1 # +1是因为新切片下标从0开始,但长度始终以buf位置为准
    def logic(buf):
        s = 0
        i = 1 #头指针
        arr = []
        while True:
            if (i >= 1024 or i>=len(buf)):
                break
            if (buf[i] == buf[i-1]): # 说明头标记已经找到
                if buf[i] == 255:
                    s = i
                    e = find_end(buf,s)
                    if e == -1:
                        i+=2
                        continue #断包丢弃
                    t = slice(s-1,e+1) # +1是因为切片不包含最后一位
                    arr.append(buf[t])
                    i = e  #在上一个尾标记之后重新开始寻找头标记
                    s = 0
                    e = 0
            i+=2
        return arr
    return logic(buf)


def FrameFilter(arr):
    '''选择优先级高的帧处理'''
    _arr = []
    if len(arr) >=2:
        for f in arr:
            try:
                cmdType = f[3]
            except Exception as e:
                continue #不是一个合法帧
            if cmdType== b'\x91':
                continue #心跳包优先级低,有交易帧时,暂不处理心跳.
            _arr.append(f)
        return _arr
    else:return arr


def FF01_TO_FF(bit):
    arr = []
    p = 1
    while p < len(bit):
        offset = 0
        char = bit[p-1] + bit[p] # 默认收录一个正常字节
        if bit[p-1] + bit[p] == "fe":
            if p+1 > len(bit) - 1 or p+2 > len(bit) - 1: #针对fe出现在最后一位的情况
                break
            if bit[p+1] + bit[p+2] == "01": #继续判断是否是需要转义字符
                char = "ff"
                offset = 2
            elif  bit[p+1] + bit[p+2] == "00": #继续判断是否是需要转义字符
                char = "fe"
                offset = 2
            else:
                return -1 #错误包
        arr.append(char)
        p+=2 + offset #每次一个字节2位 转义所以跳过偏移量为2
    return bytes.fromhex("".join(arr))


def FF_TO_FF01(bit):
    '''转义发给天线的数据'''
    res = []
    p = 1
    while p <= len(bit)-1:
        char = bit[p-1]+bit[p]
        if bit[p-1]+bit[p] == 'fe':
            char = 'fe00'
        if bit[p-1]+bit[p] == 'ff': 
            char = 'fe01'
        res.append(char)
        p+=2
    return bytes.fromhex(''.join(res))


def FORMAT_TIME(fmt):
    localTime = time.localtime(int(time.time()))
    return time.strftime(fmt, localTime)

def FORMAT_TIME2(fmt):
    timestamp = datetime.timestamp(datetime.now())
    formatted_time = datetime.fromtimestamp(timestamp).strftime(fmt)
    return formatted_time

def TIME_TO_DATA(dt, fmt):
    return int(time.mktime(time.strptime(str(dt), fmt)))



def extract_messages(buf, buf_size, head, tail):
    messages = bytearray()
    i = 0
    while i < buf_size:
        # 查找头部
        if buf[i] == (head >> 8) and buf[i+1] == (head & 0xFF):
            # 查找尾部
            j = i + 2
            while j < buf_size and buf[j] != tail:
                j += 1
            if j < buf_size:
                # 找到了一个完整的消息
                messages.extend((head >> 8).to_bytes(1, byteorder='big'))
                messages.extend((head & 0xFF).to_bytes(1, byteorder='big'))
                messages.extend(buf[i+2:j])
                messages.append(tail)
                i = j + 1
            else:
                # 没有找到尾部，跳过
                break
        else:
            # 没有找到头部，跳过
            i += 1
    return messages


def AppPrint(data:dict):
    return json.dumps(data,indent=4,ensure_ascii=False)