"""
Set Clock Script
=================
This script will let you set the time
"""
import buttons
import color
import display
import os
import utime

DISPLAY_SIZE_X = 160
DISPLAY_SIZE_Y = 80
LETTER_SIZE_X = 12
LETTER_SIZE_Y = 20
            

def main():
    setpos = 0
    COLOR_FG = color.WHITE
    COLOR_BG = color.BLACK
    last_button = 0
    while True:  
        disp = display.open()   
        pressed = buttons.read(buttons.BOTTOM_LEFT | buttons.BOTTOM_RIGHT | buttons.TOP_RIGHT)
        if pressed != last_button:
                    
            if pressed & buttons.BOTTOM_LEFT != 0:
                if setpos < 6:
                    setpos = setpos + 1
                else:
                    setpos = 0
                    
            if pressed & buttons.TOP_RIGHT != 0:
                secs = utime.time()
                if setpos == 1: secs += 36000
                if setpos == 2: secs += 3600
                if setpos == 3: secs += 600
                if setpos == 4: secs += 60
                if setpos == 5: secs += 10
                if setpos == 6: secs += 1
                utime.set_time(secs)
                
            if pressed & buttons.BOTTOM_RIGHT != 0:
                secs = utime.time()
                if setpos == 1: secs -= 36000
                if setpos == 2: secs -= 3600
                if setpos == 3: secs -= 600
                if setpos == 4: secs -= 60
                if setpos == 5: secs -= 10
                if setpos == 6: secs -= 1
                utime.set_time(secs)
                
            pressed = last_button   
            
        
        (year, month, mday, hour, min, sec, wday, yday) = utime.localtime(utime.time())
        for i in range(0, 8):
            txt = ""
            edit = False
            if i==0: 
                txt = str(int(hour / 10))
                if setpos == 1: edit = True
            if i==1: 
                txt = str(hour % 10)
                if setpos == 2: edit = True
            if i==2: 
                txt = ":"
            if i==3: 
                txt = str(int(min / 10))
                if setpos == 3: edit = True
            if i==4: 
                txt = str(min % 10)
                if setpos == 4: edit = True
            if i==5: 
                txt = ":"
            if i==6: 
                txt = str(int(sec / 10))
                if setpos == 5: edit = True
            if i==7: 
                txt = str(sec % 10)
                if setpos == 6: edit = True
            posx = int((i + 2) * LETTER_SIZE_X)
            posy = int((DISPLAY_SIZE_Y - LETTER_SIZE_Y) / 2)
            fg=COLOR_FG
            bg=COLOR_BG
            if edit:
                fg = COLOR_BG
                bg = COLOR_FG
            disp.print(txt, fg=fg, bg=bg, posx=posx, posy=posy)
            
        disp.update()
        disp.close()
   
        utime.sleep_ms(250)

if __name__ == "__main__":
    main()
