#!/usr/bin/env python
#version    :       2024.08.08
#language   :       en
from maix import display
from maix import image
from maix import camera
from maix import mjpg
from maix import utils
import base64
import time
import requests
import json
from evdev import InputDevice, categorize, ecodes
import os
import sys
sys.path.append("/root/")
sys.path.append("/root/preset/drivers/pylib/")
from CocoPi import BUTTON

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
   
camera.camera.config(size=(240,320))
image.load_freetype("/root/preset/fonts/simhei.ttf")
canvas = image.new(size = (320, 240))
try:
    # 获取键盘设备
    keyboard = InputDevice('/dev/input/event1')  # 替换成实际的键盘设备路径
except:
    keyboard = ""

if keyboard=="":
    canvas.draw_string(0,12, "Keyboard not detected", scale = 1.3, color = (255,255,255) , thickness = 1)
    display.show(canvas)
    time.sleep(3)
    sys.exit()
def v831_display_show_canvas(displayShow):
    global _canvas_y,_canvas_x
    CANVASSHOWIMGAGE = ""
    if ScreenOrientation:
        displayShowCanvas = image.new(size = (240, 320))
        displayShowCanvas.draw_rectangle(0,0,240,320, color=(0,0,0), thickness=-1)
        displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1)
        displayShowVER = displayShowCanvas.crop(0,0,240,320)
        displayShowVER = displayShowVER.rotate(-90, adjust=1)
        CANVASSHOWIMGAGE = displayShowVER
        display.show(displayShowVER)
    else:
        displayShowCanvas = image.new(size = (320, 240))
        displayShowCanvas.draw_rectangle(0,0,320,240, color=(0,0,0), thickness=-1)
        displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1)
        CANVASSHOWIMGAGE = displayShowCanvas
        display.show(displayShowCanvas)
def get_post_chatgpt(datas):
    global list_num
    # 目标URL
    url = "https://gpt.cocorobo.cn/askForTopic"
    payload = json.dumps({"topic": datas})
    headers={
        "Content-Type":"application/json"
    }
    response=requests.request("POST", url, headers=headers, data=payload)
    # try:
    #     keyboardStr[list_num] = "result"
    # except:
    #     keyboardStr[list_num] = "fail"
    #     pass
    if response.status_code == 200:
        # keyboardStr[list_num] = json.loads(response.text)["FunctionResponse"]["result"]
        result_num = len(json.loads(response.text)["FunctionResponse"]["result"])//20
        for i in range(result_num+1):
            keyboardStr.append("")
            keyboardStr[list_num] = json.loads(response.text)["FunctionResponse"]["result"][i*20:(i+1)*20]
            list_num = list_num+1
    else:
        keyboardStr[list_num] = "fail"

_canvas_x = 0
_canvas_y = 0
keyboardStr = ["Input：",""]
list_num = 1
# 判断是否联网
key_B = BUTTON(8)
key_C = BUTTON(13)
key_D = BUTTON(7)
def wifi_is_content():
    global getDateNum
    cmd = "ifconfig"

    res = os.popen(cmd).read()
    data = False
    if res.rfind("inet addr:")!=48:
        data = True

    return data


ssidInfo = ""
passwordInfo = ""
checkConnectState = False
connectText = ""
startConnect=False
wifiConnectState = False
# PublicIp=""
PrivateIP=""
runConnectSig=True
connectSuccessSig=False
while True:
    if wifi_is_content():
        break
    else:
        canvas = getLcdRotation(camera.capture())
        if ssidInfo!="" and passwordInfo!="":
            startConnect=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 startConnect==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)
                    startConnect= False
                    connectText = ""
                    checkConnectState = False
                    connectSuccessSig = False
                    wifiConnectState = False
                    runConnectSig== True
                    ssidInfo=""
                    passwordInfo=""
                if checkConnectState == True:
                    if connectSuccessSig == False:
                        # PublicIp=getPublicIp()
                        connectSuccessSig = True
                    connectText = "Wifi connection successfully！"
                    # canvas.draw_string(10,80, "The WLAN PUBLIC IP:" + PublicIp, scale = 1.5, color = (0,0,0), thickness = 1)
                    canvas.draw_string(10,110, "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=""
                    canvas.clear()
                    break
                else:
                    pass
            else:
                if checkConnectState == False:
                    os.system("wifi_disconnect_ap_test")
                    os.system('wifi_connect_chinese_ap_test '+ssidInfo+' '+passwordInfo+'')
                    checkConnectState = True
                if checkConnectState == True:
                    if key_B.is_pressed():
                        while (key_B.is_pressed() == True):
                            time.sleep(0.001)
                        startConnect= 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) , "WIFI："+ssidInfo, scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
                canvas.draw_string(int(X) , int(Y - 25) , "PSD："+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)
        v831_display_show_canvas(canvas)
# 键盘事件
canvas.draw_string(0,0, str("Input："), scale = 1, color = (255,255,255) , thickness = 1)
v831_display_show_canvas(canvas)
for event in keyboard.read_loop():
    if event.type == ecodes.EV_KEY:
        key_event = categorize(event)
        if key_event.keystate == key_event.key_down:
            # print(keyboardStr,key_event.keycode[4:].lower())
            if key_event.keycode[4:] == "SPACE":
                keyboardStr[list_num] = keyboardStr[list_num] + " "
            elif key_event.keycode[4:] == "BACKSPACE":
                keyboardStr[list_num] = keyboardStr[list_num][:-1]
                if len(keyboardStr[list_num]) ==0 and list_num>1:
                    list_num = list_num - 1
            elif key_event.keycode[4:] == "ENTER":
                keyboardStr.append("")
                list_num = list_num + 1
                get_post_chatgpt(keyboardStr[list_num-1])
            else:
                keyboardStr[list_num] = keyboardStr[list_num] + key_event.keycode[4:].lower()
            # print(list_num,keyboardStr)
            if len(keyboardStr[list_num]) >40:
                keyboardStr.append("")
                list_num = list_num + 1
            canvas.clear()
            if list_num>16:
                for i in range(list_num,list_num-16,-1):
                    canvas.draw_string(0,15*(i-(list_num-15)), str(keyboardStr[i]), scale = 1, color = (255,255,255) , thickness = 1)
            else:
                for i in range(list_num+1):
                    canvas.draw_string(0,15*i, str(keyboardStr[i]), scale = 1, color = (255,255,255) , thickness = 1)
            canvas.draw_string(0,0, str("Input："), scale = 1, color = (255,255,255) , thickness = 1)
            v831_display_show_canvas(canvas)

