#!/usr/bin/env python
#version    :       2023.12.31
#language   :       ch

from maix import camera, display, zbar, image
import socket
import os
import sys
sys.path.append('/root/')
import http.client
from CocoPi import BUTTON
import time
import json
import requests

import os
ScreenOrientation = False
try:
    if os.path.exists("/etc/cameraSize.cfg"):
        cameraSize = True
    else:
        cameraSize = False
except:
    cameraSize = False
def getLcdRotation(cameraCapture):
    global cameraSize
    if cameraSize:
        return lcdRotationNew(cameraCapture)
    else:
        return lcdRotation(cameraCapture)

def lcdRotationNew(inputImg):
    global cameraSize,ScreenOrientation
    imageRotationBuffer = inputImg.crop(0, 0, 320, 240)
    if ScreenOrientation:
        imgRotationAim = image.new(size = (240, 320))
        rotationAngle = 90
        GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
    else:
        imgRotationAim = image.new(size = (320, 240))
        GETROTATION = imageRotationBuffer

    GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
    return GETROTATION

def lcdRotation(inputImg):
    global cameraSize,ScreenOrientation
    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
    if ScreenOrientation:
        imgRotationAim = image.new(size = (240, 320))
        rotationAngle = 180
    else:
        imgRotationAim = image.new(size = (320, 240))
        rotationAngle = 90
    GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
    GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
    return GETROTATION
   
key_A = BUTTON(14)
key_B = BUTTON(8)
key_C = BUTTON(13)
key_D = BUTTON(7)

image.load_freetype("/root/preset/fonts/CascadiaCodePL-Italic.ttf")
if cameraSize==True:
    camera.camera.config(size=(320,240))
else:
    camera.camera.config(size=(240,320))
def getWifiConnectState():
    cmd = "wifi_get_connection_info_test 1"
    res = os.popen(cmd).read()
    wifiInfo = {}
    if res.find('get connection infomation successfully!') != -1:
        wifiInfo["state"]=True
        wifiInfo["AP"] = res[res.find("Connected AP: ")+13:res.find("IP address: ")-1]
        wifiInfo["IP"] = res[res.find("IP address: ")+12:res.find("frequency")-1]
        wifiInfo["frequency"] = res[res.find("frequency: ")+10:res.find("RSSI")-1]
        wifiInfo["RSSI"] = res[res.find("RSSI: ")+6:res.find("link_speed")-1]
        wifiInfo["link_speed"] = res[res.find("link_speed: ")+10:res.find("IP address: ")-1]
        wifiInfo["noise"] = res[res.find("noise: ")+6:res.find("noise: ")+11]
    else:
        wifiInfo["state"]=False
        wifiInfo["AP"] = "N/A"
        wifiInfo["IP"] = "N/A"
        wifiInfo["frequency"] = "N/A"
        wifiInfo["RSSI"] = "N/A"
        wifiInfo["link_speed"] = "N/A"
        wifiInfo["noise"] = "N/A"
    return wifiInfo
  


def urldownload(url,filepath=None,filename=None,canvas1=image.new(size = (320, 40))):
    """
    下载文件到指定目录
    :param url: 文件下载的url
    :param filename: 要存放的目录及文件名，例如：./test.xls
    :return:
    """
    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
    down_res = requests.get(url,headers=headers,stream=True)
    chunk_size = 1024 * 1024  # 单次请求最大值
    content_size = int(down_res.headers['content-length'])  # 内容体总大小
    data_count = 0
    with open(filepath,'wb') as file:
        for data in down_res.iter_content(chunk_size=chunk_size):
            file.write(data)
            data_count = data_count + len(data)
            now_jd = (data_count / content_size) * 100
            # print("\r 文件下载进度：%d%%(%d/%d) - %s" % (now_jd, data_count, content_size, filename), end=" ")
            canvas1.clear()
            canvas1.draw_string(0,0,str("Loading: ") + filename, scale = 1, color = (255, 0, 0), thickness = 2)
            canvas1.draw_string(0,20 , str("Speed: %d%%(%d/%d)" % (now_jd, data_count, content_size)), scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
            display.show(canvas1)
            # time.sleep(1)

    # return down_res.code


canvas1 = image.new(size = (320, 40))

startConnect=False
param = ''
bin = ''
py = ''
def getWifiConnectState():
    cmd = "wifi_get_connection_info_test 1"
    res = os.popen(cmd).read()
    wifiInfo = {}
    if res.find('get connection infomation successfully!') != -1:
        wifiInfo["state"]=True
        wifiInfo["AP"] = res[res.find("Connected AP: ")+13:res.find("IP address: ")-1]
        wifiInfo["IP"] = res[res.find("IP address: ")+12:res.find("frequency")-1]
        wifiInfo["frequency"] = res[res.find("frequency: ")+10:res.find("RSSI")-1]
        wifiInfo["RSSI"] = res[res.find("RSSI: ")+6:res.find("link_speed")-1]
        wifiInfo["link_speed"] = res[res.find("link_speed: ")+10:res.find("IP address: ")-1]
        wifiInfo["noise"] = res[res.find("noise: ")+6:res.find("noise: ")+11]
    else:
        wifiInfo["state"]=False
        wifiInfo["AP"] = "N/A"
        wifiInfo["IP"] = "N/A"
        wifiInfo["frequency"] = "N/A"
        wifiInfo["RSSI"] = "N/A"
        wifiInfo["link_speed"] = "N/A"
        wifiInfo["noise"] = "N/A"
    return wifiInfo

def getPrivateIp():
    st = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    try:
        st.connect(("10.255.255.255",1))
        IP = st.getsockname()[0]
    except Exception:
        IP = "127.0.0.1"
    finally:
        st.close()
    return IP

ssidInfo = ""
passwordInfo = ""
checkConnectState = False
connectText = ""
startConnectWifi=False
wifiConnectState = False
# PublicIp=""
PrivateIP=""
runConnectSig=True
connectSuccessSig=False
while True:
    canvas = getLcdRotation(camera.capture())
    IP = getPrivateIp()
    if ssidInfo!="" and passwordInfo!="":
        startConnectWifi=True
        #connectText = "Waitting for Connection..."
        #canvas.draw_string(10,40, ssidInfo+" "+str(len(ssidInfo))+" "+str(type(ssidInfo)), scale = 1.5, color = (0,0,0), thickness = 1)
        canvas.draw_string(10,50, "Connect WIFI...", scale = 1.5, color = (0,0,0), thickness = 1)
        display.show(canvas)
    if startConnectWifi==True:
        canvas_1 = image.new(size = (320, 320), color = (255,255,255), mode = "RGB")
        canvas.draw_image(canvas_1,0,0, alpha=0.4)
        if wifiConnectState == True:
            if key_B.is_pressed():
                while (key_B.is_pressed() == True):
                    time.sleep(0.001)
                startConnectWifi= False
                connectText = ""
                checkConnectState = False
                connectSuccessSig = False
                wifiConnectState = False
                runConnectSig== True
                ssidInfo=""
                passwordInfo=""
            if checkConnectState == True:
                if connectSuccessSig == False:
                    # PublicIp=getPublicIp()
                    PrivateIP=getPrivateIp()
                    connectSuccessSig = True
                connectText = "WiFi Connect Success!"
                canvas.draw_string(10,50, "WiFi Connect Success!", scale = 1.5, color = (0,0,0) , thickness = 1)
                canvas.draw_string(10,80, "IP:" + PrivateIP, scale = 1.5, color = (0,0,0), thickness = 1)
                canvas.draw_image((image.open("/root/preset/img/restart_ff0000_24x24.png")).rotate(0, adjust=0),8,216,alpha=1)
                ssidInfo=""
                passwordInfo=""
                display.show(canvas)
                time.sleep(3)
                canvas.clear()
                break
            else:
                pass
        else:
            if checkConnectState == False:
                os.system("wifi_disconnect_ap_test")
                os.system('wifi_connect_chinese_ap_test '+ssidInfo+' '+passwordInfo+'')
                wifiConnectState=getWifiConnectState()["state"]
                checkConnectState = True
            if checkConnectState == True:
                if key_B.is_pressed():
                    while (key_B.is_pressed() == True):
                        time.sleep(0.001)
                    startConnectWifi= False
                    connectText = ""
                    checkConnectState = False
                    connectSuccessSig = False
                    wifiConnectState = False
                    runConnectSig== True
                    passwordInfo = ""
                    ssidInfo = ""
                else:
                    if runConnectSig== True:
                        connectText = "Connect WIFI..."
                        runConnectSig= False
                    else:
                        passwordInfo = ""
                        ssidInfo = ""
                        connectText = "WiFi Connect Failed!"
                        canvas.draw_image((image.open("/root/preset/img/restart_ff0000_24x24.png")).rotate(0, adjust=0),8,216,alpha=1)
                
        
        canvas.draw_string(10,50, connectText, scale = 1.5, color = (0,0,0) , thickness = 1)
    else:
        mks = canvas.find_qrcodes()
        for mk in mks:
            #外框数据
            X = mk['x']
            Y = mk['y']
            W = mk['w']
            H = mk['h']            
            #二维码信息
            string = mk['payload']
            codeData = string.split(";")
            ssidInfo = codeData[0].split(":")[1]
            passwordInfo = codeData[1].split(":")[1]
            #画外框
            canvas.draw_rectangle(X, Y, X + W, Y + H, color=(0, 0, 255), thickness = 2) 
            #打印信息
            canvas.draw_string(int(X) , int(Y - 45) , "SSID:"+ssidInfo, scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
            canvas.draw_string(int(X) , int(Y - 25) , "PASSWORD:"+passwordInfo, scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
    canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
    #canvas.draw_image((image.open("/root/preset/img/camera_bfbfbf_24x24.png")).rotate(0, adjust=0),292,2,alpha=1)
    display.show(canvas)
    

while True:
    canvas = getLcdRotation(camera.capture())
    # IP = extract_ip()
    if(str(param) != '' and str(bin) != '' and str(py) != ''):
        startConnect=True
    if startConnect==True:
        canvas.clear()
        time.sleep(5)
        urldownload("https://" + bin.split("//")[1],"/root/user/model/" + (str(bin).split("newModels/")[1].split("/")[0]) + ".bin",(str(bin).split("newModels/")[1].split("/")[0]) + ".bin",canvas1)
        urldownload("https://" + param.split("//")[1],"/root/user/model/" + (str(param).split("newModels/")[1].split("/")[0]) + ".param", (str(param).split("newModels/")[1].split("/")[0]) + ".param",canvas1)
        urldownload("https://" + py.split("//")[1],"/root/" + (str(py).split("newModels/")[1].split("/")[1]),"user_latest_code.py",canvas1)
        break
    else:
        mks = canvas.find_qrcodes()
        for mk in mks:
            #外框数据
            X = mk['x']
            Y = mk['y']
            W = mk['w']
            H = mk['h']            
            #二维码信息
            try:
                string = mk['payload']
                codeData = json.loads(string)
                param = codeData['param']
                bin = codeData['bin']
                py = codeData['py']
            except:
                pass
        
            #画外框
            canvas.draw_rectangle(X, Y, X + W, Y + H, color=(0, 0, 255), thickness = 2) 
            #打印信息
            canvas.draw_string(int(X) , int(Y - 35) , str(string), scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
                
    canvas.draw_string(0, 0 , "Scan the QR code to download the model", scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
    # canvas.draw_image((image.open("/root/preset/img/camera_ff0000_24x24.png")).rotate(0, adjust=0),280,2,alpha=1)
    canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),290,208,alpha=1)
    display.show(canvas)

os.system("ln -sf %s /tmp/event && touch /tmp/start" % "/root/user_latest_code.py")