###############################################################################################################################################################################
# CampZone 2021 days countdown by [CBJ]D3xtar!
#
# This app, which is written for the CZ19 badge shows you the amount of days until the start of CampZone 2021. On the 
# last day, the display shows the hours and minutes left. Ofcourse it's an updated version of the 2020 app. But CampZone 2020 was cancelled as we all know. 
#
# In the last minute before the opening of the event the badge will countdown the final seconds. So please, wear your badge 
# proudly in the " Wachtrij" (Waitingline) of the 2021 edition of the best Outdoor Lan ever: CampZone
#
# At this moment, the real date of CampZone 2021 has not been announced yet (Steph, are you reading this? Please contact me :-)) So, at this point I
# assume that the event will start on 23-07-2021. When the exact date is announced I will update the script ASAP.
#
# This is my first serious app written in Python. So: No, it's not perfect. Yes, it contains bugs. No, it's not finished. Yes, some features will be added in the  next months. But: I think it works. 
# The code also contains some debug/test  variables and heck, it even contains variables which are not used at all at this very moment. During this year I will finetune 
# the app. Be sure you update the app before
# heading to CampZone 2021! If you have any suggestions please contact me at leonvdmeij(at)gmail.com
#
# Let's say thank you to a couple of people:
#
# The CampZone crew, for building the best Outdoor LAN event.
#
# The CZ19 badge was my first introduction to coding in Python. Big thanks to the badge.team, members of the #Hackzone field, and sponsors on CampZone for making this badge possible. 
#
# Special thanks to my very good friend [CBJ]Brain. 
#
# And of course a big thanks for my friends of Clan Badjas for their hospitality on and in the [CBJ] field and Castle on CampZone.
#
# CU in 2021!
###############################################################################################################################################################################


import time, ntp, buttons, rgb, wifi, defines, system
from default_icons import animation_connecting_wifi, icon_no_wifi


#CampZone 2021 date as calculated on: https://www.epochconverter.com/ with assumed date 23-07-2021. Timestamp is without the 7200 added GMT+2 seconds. 
#Tested with https://www.timeanddate.com/countdown/generic?iso=20200724T00&p0=4374&font=cursive

#CampZone Timestamp (not confirmed yet)
cztimestamp = 1626991200
#CBJ-LAN Timestamp
#cztimestamp = 1572012000


daysleft = 0
daysleftround = 0
olddaysleft = 400
hoursleft = 0
hoursleftround = 0
oldhoursleft = 25
minutesleft = 0
minutesleftround = 0
oldminutesleft = 70
secondsleft = 0
secondsleftround = 0
oldsecondsleft = 70
CampZonedaysleft = 11

exit = 0

rgb.brightness(10)
rgb.clear()
framerate = 15

def dateDiffInSeconds(time1, time2):
  timedelta = time2 - time1 
  return timedelta 

def daysHoursMinutesSecondsFromSeconds(seconds):
	minutes, seconds = divmod(seconds, 60)
	hours, minutes = divmod(minutes, 60)
	days, hours = divmod(hours, 24)
	global daysleft, hoursleft, minutesleft, secondsleft 
	
	#We are adding an additional day. The last day will be counted as a full day, even when is has only a couple of hours left. 
	#This is for printing the right amount of days on the display.
	
	daysleft = days +1 
	
	hoursleft = hours
	minutesleft = minutes
	secondsleft = seconds
	return (days, hours, minutes, seconds)
	
UP, DOWN, LEFT, RIGHT = defines.BTN_UP, defines.BTN_DOWN, defines.BTN_LEFT, defines.BTN_RIGHT
A, B = defines.BTN_A, defines.BTN_B

def callback_btn_B(button_is_down):
    if button_is_down:
        print("Exiting...")
        global exit
        exit = 1
		
buttons.register(defines.BTN_B, callback_btn_B)

if not wifi.status():
    data, size, frames = animation_connecting_wifi
    rgb.clear()
    rgb.framerate(3)
    rgb.gif(data, (12, 0), size, frames)
    wifi.connect()
    if wifi.wait():
        rgb.clear()
        rgb.framerate(20)
    else:
        print('No wifi')
        rgb.clear()
        rgb.framerate(20)
        data, frames = icon_no_wifi
        rgb.image(data, (12, 0), (8,8))
        time.sleep(3)
        rgb.clear()

if not wifi.status():
    print("Error connecting to wifi")
    system.reboot()

if not ntp.set_NTP_time():
    print("Error setting time")
    system.reboot()

#Setting the current time. Since the cztimestamp is provided without the GMT seconds, we will have to correct the returned time.time as well.
#Some extra timestamps a provided for testing purposes. When using these, please comment the "now = time.time() - 7200" line out in the while loop.
	
now = time.time() - 7200
#now = 1595455200  #One day left 
#now = 1595532600  #Two hours 30 minutes left 
#now = 1595534400  #Two hours left 
#now = 1595536200  #One hour 30 left
#now = 1595538000  #One hour left 
#now = 1595539840  #Half an hour left 
#now = 1595541540  #60 Seconds left 
#now = 1595541590  #10 Seconds left 
#now = 1595541610  #CampZone has started!


print("Epoch start:", (time.gmtime(0)))
print("CampZone 2021 Timestamp:", cztimestamp)
print("Current Timestamp:", now)
	

while exit != 1:

	daysHoursMinutesSecondsFromSeconds(dateDiffInSeconds(now, cztimestamp))
	daysleftround = (str(round(daysleft)))
	hoursleftround = (str(round(hoursleft)).rstrip('.'))
	minutesleftround = (str(round(minutesleft)).rstrip('.'))
	
	time.sleep(1)
		
	if daysleft>1:
			
		if daysleft != olddaysleft:
			rgb.clear()
			rgb.scrolltext((daysleftround) + ' days left until CampZone 2021!', (255, 0, 255))
			olddaysleft = daysleft
						
	else:
		
		if hoursleft > 1:
	
			if minutesleft != oldminutesleft:
				rgb.clear()
				rgb.scrolltext((hoursleftround) + ' hours and ' + (minutesleftround) + ' minutes left!',(255, 0, 255))
				oldminutesleft = minutesleft	
		
		elif hoursleft == 1:
			
			if minutesleft != oldminutesleft:
			
				rgb.clear()
				rgb.scrolltext((hoursleftround) + ' hour and ' + (minutesleftround) + ' minutes left!',(255, 0, 255))
				oldminutesleft = minutesleft
			
		
		else:		
		
			if minutesleft != oldminutesleft:	
				rgb.clear()
				rgb.scrolltext('Only ' + (minutesleftround) + ' minutes left!', (255, 0, 255))
				oldminutesleft = minutesleft
				
	now = time.time() - 7200		
		
system.reboot()