#!/usr/bin/env python
#version    :       2024.01.01
#language   :       en
from maix import *
import socket
import os
import sys
sys.path.append('/root/')
import http.client
from CocoPi import BUTTON
import time

key_A = BUTTON(14)
key_B = BUTTON(8)
key_C = BUTTON(13)
key_D = BUTTON(7)
#image.load_freetype("/root/preset/fonts/JetBrainsMono-Bold-7.ttf")
image.load_freetype("/root/preset/fonts/CascadiaCodePL-Italic.ttf")

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

def getPublicIp():
    import requests
    url = 'https://myip.ipip.net'
    res = requests.get(url).text.split(" ")
    return res[1][3:]

PublicIp=""
PrivateIP=""

baseInfo=[
        "---------------------------",
        " Design -- Create -- Share ",
        "---------------------------",
        "           SYSTEM          ",
        "***************************",
        "SystemName:    CocoPi Linux",
        "SystemVersion:   2024.01.01",
        "---------------------------",
        "  USERNAME:                ",
        "---------------------------",
        "          Internet         ",
        "***************************",
        " ",
        " ",
        " ",
        " ",
        "---------------------------",
        "Python Version        3.8.5",
        "***************************",
        "Python Package      Version",
        "***************************",
        "av                    9.2.0",
        "beautifulsoup4       4.11.1",
        "certifi           2020.6.20",
        "cffi                 1.14.3",
        "chardet               3.0.4",
        "click                 7.1.2",
        "defusedxml            0.6.0",
        "et-xmlfile            1.0.1",
        "evdev                 1.4.0",
        "Flask                 1.1.2",
        "Flask-Login           0.5.0",
        "gpiod                 1.4.0",
        "html5lib                1.1",
        "idna                   2.10",
        "itsdangerous          1.1.0",
        "jdcal                 1.4.1",
        "jieba                0.42.1",
        "Jinja2               2.11.2",
        "lxml                  4.5.2",
        "maixpy3               0.5.4",
        "MarkupSafe            1.1.1",
        "numpy                1.19.2",
        "openpyxl              3.0.5",
        "Pillow                7.2.0",
        "pip                  20.1.1",
        "plumbum               1.6.9",
        "ply                    3.11",
        "pyasn1                0.4.8",
        "PyAudio              0.2.11",
        "pycparser              2.20",
        "pylibmodbus           0.5.0",
        "pyserial                3.4",
        "qrcode                  6.1",
        "requests             2.24.0",
        "rpyc                  5.0.1",
        "rsa                     4.6",
        "schedule              0.6.0",
        "setuptools           47.1.0",
        "six                  1.15.0",
        "smbus2                0.4.2",
        "soupsieve             2.3.1",
        "spidev                  3.5",
        "SQLAlchemy           1.3.18",
        "urllib3             1.25.10",
        "websocket-client      1.5.1",
        "Werkzeug              1.0.1",
        "zbarlight               3.0",
        "---------------------------",
    ]

ownerName=""
try:
    with open( '/root/user/text/owner.txt', 'r' ) as f:
        ownerName=f.read()
except:
    ownerName="N/A"
baseInfo[8]="{: <28}".format("USERNAME:     "+ownerName)
canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
canvas.draw_string(12 , 100 , "Checking Wi-Fi connection", scale = 1, color = (255,255,255), thickness = 2)
display.show(canvas)
checkInternet=False
try:
    if getWifiConnectState()["state"]==True:
        PublicIp=getPublicIp()
        PrivateIP=getPrivateIp()
        baseInfo[12]="{: <28}".format("PublicIP:"+PublicIp)
        baseInfo[13]="{: <28}".format("PrivateIP:"+PrivateIP)
        baseInfo[14]="{: <28}".format("WIFI AP:"+getWifiConnectState()["AP"])
        baseInfo[15]="{: <28}".format("WIFI RSSI:"+getWifiConnectState()["RSSI"])
    else:
        PublicIp="N/A"
        PrivateIP="N/A"
        baseInfo[12]="{: <28}".format("PublicIP:    N/A")
        baseInfo[13]="{: <28}".format("PrivateIP:   N/A")
        baseInfo[14]="{: <28}".format("WIFI AP:    N/A")
        baseInfo[15]="{: <28}".format("WIFI RSSI:   N/A")
except:
    PublicIp="N/A"
    PrivateIP="N/A"
    baseInfo[12]="{: <28}".format("PublicIP:    N/A")
    baseInfo[13]="{: <28}".format("PrivateIP:   N/A")
    baseInfo[14]="{: <28}".format("WIFI AP:    N/A")
    baseInfo[15]="{: <28}".format("WIFI RSSI:   N/A")
    pass

xPosition=48
yPosition=160
ySpeedMax=12
yDirection=0
yRealSpeed=0
totalNum=0
while True:
    canvas.clear()
    canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
    if key_D.is_pressed():
        yDirection=-1
    elif key_B.is_pressed():
        yDirection=1
    else:
        yDirection=0
    if yDirection==1:
        if yRealSpeed<(ySpeedMax*yDirection):
            yRealSpeed=yRealSpeed+1
        else:
            yRealSpeed=yRealSpeed
    elif yDirection==-1:
        if yRealSpeed>(ySpeedMax*yDirection):
            yRealSpeed=yRealSpeed-1
        else:
            yRealSpeed=yRealSpeed
    else:
        if yRealSpeed>0:
            yRealSpeed=yRealSpeed-1
        elif yRealSpeed<0:
            yRealSpeed=yRealSpeed+1
        else:
            yRealSpeed=0
    yPosition=yPosition+yRealSpeed
    if yPosition>160:
        yPosition=160
    elif yPosition<-900:
        yPosition=-900
    else:
        yPosition=yPosition
    #canvas.draw_string(60 , 8 , "yPosition:"+str(yPosition)+"yRealSpeed:"+str(yRealSpeed), scale = 1, color = (255,255,255), thickness = 1)
    canvas.draw_image(image.open("/root/preset/img/cocorobo_152146.png"),xPosition+40 , yPosition-144,alpha=1)
    canvas.draw_image(image.open("/root/preset/img/cocorobo_text.jpg"),xPosition+32 , yPosition-20,alpha=1)

    for i in range(len(baseInfo)):
        if  (yPosition+(i)*16)<260 and (yPosition+(i)*16)>-20:
            canvas.draw_string(xPosition , yPosition+i*16 , baseInfo[i], scale = 1, color = (255,255,255), thickness = 1)
        else:
            pass
    canvas.draw_image((image.open("/root/preset/img/left_ffffff_16x16.png")).rotate(90, adjust=0),6,6,alpha=1)
    canvas.draw_image((image.open("/root/preset/img/left_ffffff_16x16.png")).rotate(270, adjust=0),6,216,alpha=1)
    canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
    display.show(canvas)