#!/usr/bin/env python
#version    :       2023.04.04
#language   :       en
from maix import display
from maix import image
from maix import camera
import time
import sys
sys.path.append('/root/')
from CocoPi import BUTTON
# 秒表小程序
key_C = BUTTON(13)
key_B = BUTTON(8)
camera.camera.config(size=(320,240))
image.load_freetype("/root/preset/fonts/CascadiaCodePL-Italic.ttf")
signal=0
startPointer=0
startTime=0
global deltaTime
deltaTime=0
# 初始化
startTime = time.time()
oldState=0
newState=0
canvas = image.new(color=(0,0,0),size = (320, 240))
while True:
    canvas.clear()
    if key_B.is_pressed():
        time.sleep(0.02)
        deltaTime = 0
        startTime = round(time.time(), 3)
    else:
        pass
    newState=key_C.is_pressed()
    if (newState==0 and oldState==1):
        time.sleep(0.02)
        signal=1-signal
        if deltaTime == 0:
            startTime = round(time.time(), 3)
        else:
            startTime =  round(time.time(), 3) - deltaTime
    else:
        pass
    if signal==1:
        if startPointer==0:
            startPointer=1
            #print("startPoniter",startPoniter)
        else:
            #pass
            deltaTime = round(time.time() - startTime, 3)
            #deltaTime = time.time()-startTime
            #deltaTime = round(time.time()-startTime, 5)
            #canvas.draw_string(80, 128, "lastTime:"+str(deltaTime), 1, color=(0, 255, 0))
        
    elif signal==0:
        startPointer=0
    else:
        pass
    if signal==1:
        canvas.draw_string(80, 108, "Counter is working...", 1, color=(0, 255, 0))
        canvas.draw_image((image.open("/root/preset/img/stop24.png")).rotate(0, adjust=0),288,2,alpha=1)
    else:
        canvas.draw_string(80, 108, "Counter is waitting...", 1, color=(0, 255, 0))
        canvas.draw_image((image.open("/root/preset/img/play24.png")).rotate(0, adjust=0),288,2,alpha=1)
    canvas.draw_string(100, 128, "Lasttime:"+str(deltaTime), 1, color=(0, 255, 0))
    canvas.draw_string(16, 8, "Press KEY-C to start/stop Counter", 1, color=(0, 255, 0))
    
    canvas.draw_image((image.open("/root/preset/img/restart_ff0000_24x24.png")).rotate(0, adjust=0),2,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)
    oldState=newState
