#!/usr/bin/env python
#version    :       2023.06.15
#language   :       ch
#hardware   :       pi

import time
from maix import *
import gc
import os,sys
import sys
sys.path.append('/root/')
from CocoPi import BUTTON
from CocoPi import stm8s
from CocoPi import multiFuncGpio

gc.enable()
gc.collect()
iic_slaver=stm8s()
iic_slaver.clear()
PIXEL_LED1= multiFuncGpio(0,7)
PIXEL_LED2= multiFuncGpio(1,7)
PIXEL_LED1.pixelInit_()
PIXEL_LED2.pixelInit_()
time.sleep(0.01)
del iic_slaver
del PIXEL_LED1
del PIXEL_LED2

count = 0

def gc_log():
    global count
    gc.collect()
    count = count + 1

splash_theme_color = (15,21,46)
btn_selected = (255,255,255)
btn_unselected = (76,86,127)
txt_selected = (255,255,255)
txt_unselected = (76,86,127)
color_splash_theme = (15,21,46)
color_blue = (31,61,185)
color_blue_lighter = (60,131,211)
color_white = (255,255,255)
color_gray = (60,73,126)
color_orange = (255,165,0)
color_red = (255,0,0)


btn_width = 134
btn_height = 52
btn_y_base = 5
btn_col = (btn_y_base, btn_y_base+btn_width, btn_y_base+152)
btn_row = 180

main_title = (
        "运行",
        "上次程序",
        "打开",
        "样例菜单",
        "B",
        "A"
    )
splash_text = (
        "系统版本: 2023-06-15 en branch",
        "System version: N/A",
        "2. 加载程序后，按下A键两秒退出程序界面.",
        "    ",
        "    ",
        "启动上次程序中...",
        "错误: 未找到程序...",
        "错误: 语法有误",
        "正在打开样例菜单...",
        "未找到样例菜单.",
        "运行",
        "加载...",
        "返回",
        "按下C键返回主界面",
        "按下D键重启",
        "按下B键关机",
        "1. 按下A键七秒来关闭或者重启CocoPi系统.",
        "    ",
        "    ",
        "CocoPi V6",
        "/ Linux / AIot /Python /",
        "/Graphical programming /",
        "------------- 基础 --------------",
        "----------- 人工智能 ----------",
        "------------ 物联网 ------------",
    )

title_logo_text = image.open("/root/preset/img/cocorobo_text.jpg")
iconUpNp = image.open("/root/preset/img/arrow_up_filled.jpg")
iconUpP = image.open("/root/preset/img/arrow_up_pressed.jpg")
iconDownNp = image.open("/root/preset/img/arrow_down_filled.jpg")
iconDownP = image.open("/root/preset/img/arrow_down_pressed.jpg")
frostedGlass = image.open("/root/preset/img/frostedglass_.jpg")
#backUp = image.open("/root/preset/img/backup_48x48.png")
#powerOff = image.open("/root/preset/img/poweroff_48x48.png")
#reBoot = image.open("/root/preset/img/reboot_48x48.png")

run_user_code_path='/root/user_latest_code.py'
run_try_demo_path='/root/play_music.py'


key_A = BUTTON(14)
key_B = BUTTON(8)
key_C = BUTTON(13)
key_D = BUTTON(7)

splash = image.new(size=(320, 240),mode = "RGB")
img_drop=image.new(size=(320,240),mode="RGB")

demo_i=0
demo_j=0
demo_m=0
demo_n=0
pressTime=0
systemRunNum=0

image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
def screenFirstPage():
    from maix import display,image,camera
    global splash,title_logo_text,btn_col,btn_row,splash_text,txt_unselected,txt_selected,btn_selected,btn_unselected,\
splash_theme_color,btn_height,btn_width,main_title,menuSelect,gc_log,demo_i,demo_j,demo_m,demo_n,screenShow,img_drop,\
frostedGlass
    gc_log()
    image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
    splash.clear()
    splash.draw_rectangle(0,0,320,320,color=splash_theme_color,thickness=-1)
    splash.draw_image(title_logo_text, btn_col[0]+16, 10)
    x, y = image.get_string_size(splash_text[0], 1)

    splash.draw_string(btn_col[0]+16, 40, splash_text[19]+"  "+splash_text[0], color=(0,255,255), thickness = 1)
#    splash.draw_string(btn_col[0], 60, splash_text[20], color=(0,255,255), thickness = 1)
#    splash.draw_string(btn_col[0], 80, splash_text[21], color=(0,255,255), thickness = 1)
#    splash.draw_string(btn_col[0], 60, splash_text[0], color=(0,255,255), thickness = 1)
    splash.draw_string(btn_col[0]+16, btn_row-105, splash_text[16], color=txt_unselected, thickness = 1)
    splash.draw_string(btn_col[0]+16, btn_row-85, splash_text[17], color=txt_unselected, thickness = 1)
    #splash.draw_string(btn_col[0], btn_row-105, splash_text[18], color=txt_unselected, thickness = 1)
    splash.draw_string(btn_col[0]+16, btn_row-65, splash_text[2], color=txt_unselected, thickness = 1)
    splash.draw_string(btn_col[0]+16, btn_row-45, splash_text[3], color=txt_unselected, thickness = 1)
    splash.draw_string(btn_col[0]+16, btn_row-25, splash_text[4], color=txt_unselected, thickness = 1)

    if menuSelect==0:
        splash.draw_rectangle(btn_col[1]+40, btn_row, btn_col[1]+btn_width+42, btn_row+btn_height, color=btn_selected, thickness=1)
        splash.draw_string(btn_col[1]+52, btn_row+7, main_title[2], color=txt_selected, thickness = 1)
        splash.draw_string(btn_col[1]+52, btn_row+27, main_title[3], color=txt_selected, thickness = 1)
        splash.draw_string(btn_col[1]+157, btn_row+27, main_title[5], color=txt_unselected, thickness = 1)

        splash.draw_rectangle(btn_col[0], btn_row, btn_col[0]+btn_width, btn_row+btn_height, color=btn_selected, thickness=1)
        splash.draw_string(btn_col[0]+96, btn_row+7, main_title[0], color=txt_selected, thickness = 1)
        splash.draw_string(btn_col[0]+68, btn_row+27, main_title[1], color=txt_selected, thickness = 1)
        splash.draw_string(btn_col[0]+7, btn_row+27, main_title[4], color=txt_unselected, thickness = 1)

    if menuSelect==1:
        splash.draw_rectangle(btn_col[0], btn_row, btn_col[0]+btn_width, btn_row+btn_height, color=btn_unselected, thickness=1)
        splash.draw_string(btn_col[0]+7, btn_row+7, main_title[0], color=txt_unselected, thickness = 1)
        splash.draw_string(btn_col[0]+7, btn_row+27, main_title[1], color=txt_unselected, thickness = 1)

        splash.draw_rectangle(btn_col[1], btn_row, btn_col[1]+btn_width, btn_row+btn_height, color=btn_selected, thickness=1)
        splash.draw_string(btn_col[1]+7, btn_row+7, main_title[2], color=txt_selected, thickness = 1)
        splash.draw_string(btn_col[1]+7, btn_row+27, main_title[3], color=txt_selected, thickness = 1)

    splash.draw_image(frostedGlass, 0, 0,alpha=0.2)
    #screenShow()
    display.show(splash)

def screenSecondPage():
    from maix import display, image,camera
    global splash,title_logo_text,btn_col,btn_row,splash_text,txt_unselected,txt_selected,btn_selected,btn_unselected,\
splash_theme_color,btn_height,btn_width,main_title,demoSelect,gc_log,color_splash_theme,color_blue,color_blue_lighter,\
color_white,color_gray,color_orange,color_red,iconUpNp,iconUpP,iconDownNp,iconDownP,demoListText,screenShow,img_drop,\
frostedGlass
    gc_log()
    image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
    splash.clear()
    splash.draw_rectangle(0,0,320,240,color=splash_theme_color,thickness=-1)
    splash.draw_rectangle(0,0,320,32,color=color_blue,thickness=-1)
    splash.draw_image(iconUpNp, 3, 3)
    splash.draw_image(iconDownNp, 287, 3)

    splash.draw_rectangle(0,214,50,240,color=color_blue,thickness=-1)
    splash.draw_rectangle(270,214,320,240,color=color_blue,thickness=-1)
    splash.draw_string(12, 218, splash_text[10], color=(255,255,255), thickness = 1)
    splash.draw_string(282, 218, splash_text[12], color=(255,255,255), thickness = 1)

    demo_i=int(demoSelect/6)
    demo_j=demoSelect%6
    demo_m=int(demoNum/6)
    demo_n=demoNum%6
    for j in range(6):
        if demo_i==demo_m:
            if j>=demo_n:
                pass
            else:
                if j==demo_j:
                    pass
                else:
                    splash.draw_rectangle(0,33+30*j,319,33+30*(j+1),color=color_gray,thickness=1)
                    splash.draw_string(8, 39+30*j,demoListText[j+demo_i*6] , color=color_gray, thickness = 1)
        else:
            if j==demo_j:
                pass
            else:
                splash.draw_rectangle(0,33+30*j,319,33+30*(j+1),color=color_gray,thickness=1)
                splash.draw_string(8, 39+30*j,demoListText[j+demo_i*6] , color=color_gray, thickness = 1)
    if demoSelect<13:
        splash.draw_string(72, 10, splash_text[22], color=(255,255,255), thickness = 1)
    elif demoSelect<23:
        splash.draw_string(72, 10, splash_text[23], color=(255,255,255), thickness = 1)
    else:
        splash.draw_string(72, 10, splash_text[24], color=(255,255,255), thickness = 1)
    splash.draw_rectangle(0,33+30*demo_j,319,33+30*(demo_j+1),color=color_white,thickness=1)
    splash.draw_string(8, 39+30*demo_j,demoListText[demoSelect] , color=color_white, thickness = 1)
    splash.draw_string(146, 218, str(demoSelect+1), color=(255,255,255), thickness = 1)
    splash.draw_string(160, 218, "/"+str(demoNum), color=(255,255,255), thickness = 1)
    splash.draw_image(frostedGlass, 0, 0,alpha=0.2)
    #screenShow()
    display.show(splash)

def systemPage():
    from maix import display, image,camera
    import time
    global splash,title_logo_text,btn_col,btn_row,splash_text,txt_unselected,txt_selected,btn_selected,btn_unselected,\
splash_theme_color,btn_height,btn_width,main_title,demoSelect,gc_log,color_splash_theme,color_blue,color_blue_lighter,\
color_white,color_gray,color_orange,color_red,iconUpNp,iconUpP,iconDownNp,iconDownP,demoListText,screenShow,img_drop,\
frostedGlass
    image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
    for i in range(10):
        splash.draw_image(frostedGlass, 0, 0,alpha=0.2)
        #screenShow()
        display.show(splash)
    splash.draw_string(80, 68, splash_text[13], 1,color=(0,255,0), thickness = 1)
    splash.draw_string(80, 118, splash_text[14], 1,color=(255,255,0), thickness = 1)
    splash.draw_string(80, 168, splash_text[15], 1,color=(255,0,0), thickness = 1)
    #splash.draw_image(backUp, 20, 140)
    #screenShow()
    splash.draw_image((image.open("/root/preset/img/backup_00ff00_32x32.png")).rotate(0, adjust=0),40,60,alpha=1)
    splash.draw_image((image.open("/root/preset/img/reboot_ffff00_32x32.png")).rotate(0, adjust=0),40,110,alpha=1)
    splash.draw_image((image.open("/root/preset/img/poweroff_ff0000_32x32.png")).rotate(0, adjust=0),40,160,alpha=1)

    display.show(splash)

pageVal=0
menuSelect=0
demoSelect=0
execVal=0
demoListText=(
    "相机",
    "相册",
    "颜色分析",
    "录音机",
    "音频播放器",
    "播放演示音乐",
    "播放演示视频",
    "秒表计时器",
    "系统时钟显示",
    "舵机操控",
    "电机操控",
    "图片轮播",
    "二维码扫描",
    "人形识别",
    "人脸检测",
    "人脸比对",
    "物体识别",
    "边缘检测",
    "手写数字识别",
    "车牌识别",
    "口罩识别",
    "手势识别",
    "猜拳识别",
    "扫码连接WIFI",
    "关于CocoPi",
    "无线相机",
    "网络天气",
    "网络时钟",
    "环境监测",
    "模型训练：数据集采集",
    "模型训练：模型部署",
    "切换语言",
    "检查更新",
    "撤销更新",

)
demoNameList=(
    "01_camera",
    "02_photoViewer",
    "03_colorDetection",
    "04_recorder",
    "05_audioPlayer",
    "06_musicPlayer",
    "07_videoPlayer",
    "08_timeCounter",
    "09_localTimeClock",
    "10_servoControl",
    "11_motorControl",
    "12_pictureLoopPlay",
    "13_qrCodeScanner",
    "14_humanDetection",
    "15_faceDetection",
    "16_faceComparison",
    "17_objectRecognition",
    "18_edgeDetection",
    "19_handWrittenDigiRecognition",
    "20_carLicensePlateRecognition",
    "21_maskDetection",
    "22_gestureRecognition",
    "23_fingerGuessing",
    "24_connectWifi",
    "25_aboutCocoPi",
    "26_internetCamera",
    "27_internetWeatherPrediction",
    "28_internetTimeClock",
    "29_environmentDetection",
    "30_train_data_collect",
    "31_train_deploy_model",
    "checkout",
    "pull",
    "reset",

)
demoNum=len(demoListText)
pageSig=1
selectSig=1
def buttonDectect():
    from maix import display, image,camera
    import time
    import os
    global key_A,key_B,key_C,key_D,pageVal,menuSelect,execVal,demoNum,demoSelect,splash,iconUpP,iconDownP,screenShow,img_drop,systemRunNum,pageSig,selectSig

    if(pageVal==0):
        if(key_A.is_pressed()):
            pressTime=time.perf_counter()
            while key_A.is_pressed()==1:
                if(time.perf_counter()-pressTime)<5:
                    time.sleep(0.001)
                    pageVal=1
                else:
                    pageVal=2
                    break
            execVal=0
        elif(key_B.is_pressed()):
            while key_B.is_pressed()==1:
                time.sleep(0.001)
            execVal=1
#         elif (key_B.is_pressed()):
#             while key_B.is_pressed()==1:
#                 time.sleep(0.001)
#             pageVal=1
        else:
            pass
    elif(pageVal==1):
        if execVal==0:
            if(key_D.is_pressed()):
                splash.draw_image(iconUpP, 3, 3)
                #screenShow()
                display.show(splash)
                while key_D.is_pressed()==1:
                    time.sleep(0.001)
                demoSelect=demoSelect-1
                if(demoSelect==-1):
                    demoSelect=demoNum-1
            elif (key_C.is_pressed()):
                splash.draw_image(iconDownP, 287, 3)
                #screenShow()
                display.show(splash)
                while key_C.is_pressed()==1:
                    time.sleep(0.001)
                demoSelect=demoSelect+1
                if(demoSelect==demoNum):
                    demoSelect=0
            elif (key_B.is_pressed()):
                while key_B.is_pressed()==1:
                    time.sleep(0.001)
                execVal=2+demoSelect
            elif (key_A.is_pressed()):
                while key_A.is_pressed()==1:
                    time.sleep(0.001)
                menuSelect=0
                pageVal=0
                demoSelect=0
                execVal=0
                try:
                    with open( '/tmp/page.txt', 'w' ) as f:
                        f.write(str(pageVal))
                except:
                    pass
                try:
                    with open( '/tmp/menu.txt', 'w' ) as f:
                        f.write(str(demoSelect))
                except:
                    pass
                pageSig=1
                selectSig=1
            else:
                pass
        else:
            if (key_A.is_pressed()):
                while key_A.is_pressed()==1:
                    time.sleep(0.001)
                menuSelect=0
                pageVal=0
                demoSelect=0
                execVal=0
                systemRunNum=0
    elif pageVal==2:
        if(key_C.is_pressed()):
            pageVal=0
            menuSelect=0
            pageVal=0
            demoSelect=0
            execVal=0
            systemRunNum=0
        elif key_B.is_pressed():
            os.system("poweroff")
        elif key_D.is_pressed():
            os.system("reboot")
    else:
        pass

def running():
    from maix import display, image,camera
    global splash,title_logo_text,btn_col,btn_row,splash_text,txt_unselected,txt_selected,btn_selected,btn_unselected,\
splash_theme_color,btn_height,btn_width,main_title,menuSelect,pageVal,execVal,screenFirstPage,screenSecondPage,\
color_splash_theme,color_blue,color_blue_lighter,color_white,color_gray,color_orange,color_red,demo_i,demo_j,\
demo_m,demo_n,screenShow,img_drop,systemRunNum,systemPage,demoNameList,pageSig,selectSig,demoSelect
    if pageSig==1:
        try:
            with open( '/tmp/page.txt', 'r' ) as f:
                pageVal=int(f.read())
                print(pageVal)
            pageSig=0
        except:
            pass
    if selectSig==1:
        try:
            with open( '/tmp/menu.txt', 'r' ) as f:
                demoSelect=int(f.read())
                print(demoSelect)
            selectSig=0
        except:
            pass

    if(pageVal==0):
        screenFirstPage()
        if(execVal==0):
            pass
            #splash.draw_rectangle(btn_col[0], btn_row-26,btn_col[0]+220,26, color=splash_theme_color, thickness=1)
            #screenShow()
            #display.show(splash)
        else:
            try:
                splash.draw_string(btn_col[0], btn_row-25, splash_text[5], color=(0,255,255),thickness = 1)
                #screenShow()
                display.show(splash)
                time.sleep(0.5)
                os.system("ln -sf %s /tmp/event && touch /tmp/start" % "/root/user_latest_code.py")

            except BaseException as e:
                execVal=0
                print(str(e))
                splash.draw_rectangle(btn_col[0], btn_row-26,btn_col[0]+220,26, color=splash_theme_color, thickness=1)
                splash.draw_string(btn_col[0], btn_row-85, splash_text[9], color=(255,0,0), thickness = 1)
                #screenShow()
                display.show(splash)
    elif(pageVal==1):
        if(execVal==0):
            screenSecondPage()
            #print("show(demoSelect)")
        else:
            demo_i=int(demoSelect/6)
            demo_j=demoSelect%6
            demo_m=int(demoNum/6)
            demo_n=demoNum%6
            splash.draw_rectangle(0,33+30*demo_j,319,33+30*(demo_j+1),color=color_orange,thickness=-1)
            splash.draw_rectangle(0,33+30*demo_j,319,33+30*(demo_j+1),color=color_white,thickness=1)
            splash.draw_string(8, 39+30*demo_j,splash_text[11] , color=color_white, thickness = 1)
            #screenShow()
            display.show(splash)
            time.sleep(0.5)
            app_path_1='ln -sf /root/preset/app/'
            app_path_2='.py /tmp/event && touch /tmp/start'
            app_path=app_path_1+demoNameList[execVal-2]+app_path_2
            #print(app_path)
            try:
                with open( '/tmp/page.txt', 'w' ) as f:
                    f.write(str(pageVal))
            except:
                pass
            try:
                with open( '/tmp/menu.txt', 'w' ) as f:
                    f.write(str(demoSelect))
            except:
                pass
            pageSig=1
            selectSig=1
            os.system(app_path)
    else:
        if systemRunNum==0:
            systemPage()
            systemRunNum=systemRunNum+1
        else:
            pass

def screenShow():
    from maix import image,display,camera
    global img_drop
    screenCapture=splash.crop(0,0,240,320)
    img_drop.draw_image((screenCapture.rotate(0,adjust=1)),0,0)
    #img_drop.draw_image((screenCapture.rotate(-90,adjust=1)),0,0)
    display.show(img_drop)
try:
    with open( '/tmp/filesyStem.txt', 'w' ) as f:
        f.write("a")
    #os.system("rm /etc/wifi/wpa_supplicant.conf && touch /etc/wifi/wpa_supplicant.conf && sync && fsck.ext4 -p /dev/root && mount -o remount -o rw /dev/root && rm /etc/wifi/wpa_supplicant.conf && touch /etc/wifi/wpa_supplicant.conf && sync &")
    os.system("sync && rm /tmp/filesyStem.txt && sync")
    #os.system("fsck.ext4 -p /dev/root && mount -o remount -o rw /dev/root")
    #os.system("rm /etc/wifi/wpa_supplicant.conf && touch /etc/wifi/wpa_supplicant.conf && sync")
    
except:
    os.system("fsck.ext4 -p /dev/root && mount -o remount -o rw /dev/root")

try:
    os.popen("cd /root/preset/server/ && python wirelessServer.py &")
except:
    pass
while True:
    buttonDectect()
    running()

del key_A
del key_B
del key_C
del key_D



