import shutil
import sys
import os
import prebuild as time



# 定义app和boot文件路径(没有尾缀)
APP_FILE_SRC = "./Objects/app/checker_slave_app"
BOOT_FILE_SRC = "./Objects/boot/checker_slave_boot"
# APP_FILE_DST = "./Objects/checker_slave_app"
APP_FILE_DST = "./python/file/checker_slave_app"
BOOT_FILE_DST = "./Objects/checker_slave_boot"

# 定义app和boot的数据库目录
SQL_APP_PATH = "checker_slave_app"
SQL_BOOT_PATH = "checker_slave_boot"



# 找到指定后缀的文件
def find_type(fix:str):
    path = os.getcwd()
    #print(path)
    list=os.listdir(path)
    file_list=[]
    for i in list:
        if(i[-len(fix):]==fix):
            file_list.append(i)
    return file_list


# 把ext_name打包到name之后
def pack_file(name,ext_name):
    with open(name, "ab") as f:
        data=bytearray(256)
        data[4:len(ext_name)+4]=bytearray(ext_name,"utf-8")
        with open(ext_name,"rb") as g:
            g.seek(0, os.SEEK_END)
            size=g.tell()+256
            g.seek(0, os.SEEK_SET)
            data[0]=size&0xff
            data[1]=(size>>8)&0xff
            data[2]=(size>>16)&0xff
            data[3]=(size>>24)&0xff
            print("name:",ext_name,"size=",size)
            f.write(data)
            f.write(g.read())




def crc32(data:bytearray):
    temp=0
    crc=0xffffffff
    i=0
    if(len(data)%4!=0):
        return 0
    while(i<len(data)):
        temp=data[i]|(data[i+1]<<8)|(data[i+2]<<16)|(data[i+3]<<24)
        i+=4
        for j in range(32):
            if((crc^temp)&0x80000000)!=0:
                crc=0x04c11db7^(crc<<1)
            else:
                crc<<=1
            temp<<=1
        crc&=0xffffffff
    return crc





# 运行地址为 0x08004000
# 添加一个128byte为本程序添加的数据头



# 数据头定义：
# 固件大小(4byte,不包含文件头)
# 打包时间(20byte,字符串,本程序创建的时间)
# CRC(4byte,整个固件的crc,计算crc不包含文件头)
# 本机IP地址(4byte,按字节为单位依次存储ip地址)
# 主机IP地址(4byte,同上)
# 主机TCP端口(4byte)
# 与主机的通信接口(8byte,字符串)
# 不足128byte的补0


# 填充指定个数的byte
def arr_byte_copy(byte:int,num:int):
    t=bytearray()
    for i in range(num):
        t.append(byte)
    return t
# int转数组
def arr_from_int(num:int):
    return  bytearray([num&0xff,(num>>8)&0xff,(num>>16)&0xff,(num>>24)&0xff])
# uchar转数组
def arr_from_uchar(num:int):
    return bytearray([num&0xff])
# u16转数组
def arr_from_u16(num:int):
    return  bytearray([num&0xff,(num>>8)&0xff])
# 字符串转数组，不足填充0
def arr_from_str(txt:str,num:int):
    t=bytearray(txt.encode(encoding="utf-8"))
    t+=arr_byte_copy(0,num-len(t))
    return t
# ip地址转数组
def arr_from_ip(ip:str):
    nums=ip.split('.')
    t=bytearray()
    t.append(int(nums[0]))
    t.append(int(nums[1]))
    t.append(int(nums[2]))
    t.append(int(nums[3]))
    return t

# 创建数据头
def creat_head(data:bytearray,date:str):
    head=bytearray()
    head+=arr_from_int(len(data))
    head+=arr_from_str(date,20)
    head+=arr_from_int(crc32(data))
    head+=arr_from_ip("192.168.80.10")
    head+=arr_from_ip("192.168.80.100")
    head+=arr_from_int(7777)
    head+=arr_from_str("utcp",8)
    head+=arr_from_str("slave",12)
    head+=arr_byte_copy(0,128-len(head))
    # print(head)
    return head


def main():
    date=time.get_date()
    src=APP_FILE_SRC+".bin"
    dst=APP_FILE_DST+"_"+date+".pkt"
    if not os.path.exists(src):
        print(src+' File Error!!!')
    else:

        if os.path.exists(dst):
            os.remove(dst)
        file = open(src,"rb")
        data = file.read()
        print("File Size is :", len(data))
        file.close()
        head=creat_head(data,time.get_time())
        data=head+data
        with open(dst,"wb") as f:
            f.write(data)
        print(dst+' create app file success.')
        readback=os.popen("upload "+SQL_APP_PATH+" "+dst).readlines()
        for i in readback:
            print(i)
        # sql=mysql.sql()
        # if(sql.init(SQL_APP_PATH)==True):
        #     sql.insert(dst)
    boot=BOOT_FILE_SRC+".bin"
    boot_dst=BOOT_FILE_DST+"_"+date+".bin"
    if os.path.exists(boot):
        d=bytearray()
        with open(boot,"rb") as f:
            d+=f.read()
        d+=arr_byte_copy(0xff,0x4000-len(d))
        with open(src,"rb") as f:
            d+=f.read()
        if os.path.exists(boot_dst):
            os.remove(boot_dst)
        with open(boot_dst,"wb") as f:
            f.write(d)
            print(boot_dst+" create boot file success.")
            #sql=mysql.sql()
            #if(sql.init(SQL_BOOT_PATH)==True):
            #    sql.insert(boot_dst)
    else:
        print("please build bootloader to create boot file")
if __name__=="__main__":
    main()

