import time
from datetime import datetime
from rgbmatrix import RGBMatrix, RGBMatrixOptions, graphics
import pytz
import json

try:
    with open('clock_screensaver.json', 'r') as f:
        settings = json.load(f)['world_clock']
except:
    settings1 = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
    with open('clock_screensaver.json', 'w') as f:
        json.dump(settings1, f)
    settings = settings1['world_clock']

options = RGBMatrixOptions()
options.rows = 32
options.cols = 128
options.chain_length = 1
options.parallel = 1
options.hardware_mapping = 'adafruit-hat'  # Change this if you have a different GPIO mapping
options.gpio_slowdown = 2
options.brightness = int(settings['brightness'])*10
matrix = RGBMatrix(options=options)
canvas = matrix.CreateFrameCanvas()

font = graphics.Font()
#font.LoadFont("fonts/clR6x12.bdf")
#font.LoadFont("fonts/6x12.bdf")  # Change this to the path of your desired font file

city_colors = {
    "White": graphics.Color(255,255,255),
    "Red": graphics.Color(255, 0,0),
    "Green": graphics.Color(0,255,0),
    "Dark Green": graphics.Color(0, 100,0),
    "Blue": graphics.Color(0,0,255),
    "Purple": graphics.Color(145,0,255),
    "Pink": graphics.Color(255,0,255),
    "Yellow": graphics.Color(255,255,0),
    "Orange": graphics.Color(255,130,0),
    "Gold": graphics.Color(255,190,0),
    "Gray": graphics.Color(100,100,100),
    "Cyan": graphics.Color(0,255,255)
}

color = city_colors[settings['city_color']]
line_c = graphics.Color(50,50,50)
font.LoadFont("fonts/5x7.bdf")

time_colors = {
    "day": graphics.Color(255, 191, 0),  # Orange color
    "night": graphics.Color(0, 71,171),  # Dark blue / purple color
}


# settings = {'display_seconds': True, 'display_pm': True, '12hour': False}

def getTimes(timezone):

    if settings['12hour']:
        if settings['display_pm'] and settings['display_seconds']:
            time = datetime.now(timezone).strftime("%I:%M:%S %p")
        elif settings['display_pm'] and not settings['display_seconds']:
            time = datetime.now(timezone).strftime("%I:%M %p")
        elif not settings['display_pm'] and settings['display_seconds']:
            time = datetime.now(timezone).strftime("%I:%M:%S %p")
        else:
            time = datetime.now(timezone).strftime("%I:%M %p")
    else:
        if settings['display_pm'] and settings['display_seconds']:
            time = datetime.now(timezone).strftime("%H:%M:%S %p")
        elif settings['display_pm'] and not settings['display_seconds']:
            time = datetime.now(timezone).strftime("%H:%M %p")
        elif not settings['display_pm'] and settings['display_seconds']:
            time = datetime.now(timezone).strftime("%H:%M:%S %p")
        else:
            time = datetime.now(timezone).strftime("%H:%M %p")

    return time

def isDaytime(time):
    if settings['12hour']:
        hour = int(time.split(':')[0])
        daytime_start_hour = 6
        daytime_end_hour = 6
        am_pm = time[-2:]
        if (6 <= hour <= 11 and am_pm == 'AM') or (1 <= hour <= 6 and am_pm == 'PM') or (hour == 12 and am_pm == 'PM'):
            return True
        else:
            return False

#    if settings['12hour']:
#        hour = time.split(':')[0]
#        daytime_start_hour = 6
#        daytime_end_hour = 6
#        print(time)
#        if ((6 <= int(hour) <= 11) and time[-2:] == 'AM') or ((12 <= int(hour) <= 6) and time[-2:] == 'PM'):
#            return True
#        else:
#            return False
    else:
        hour = time.split(':')[0]
        daytime_start_hour = 6
        daytime_end_hour = 18

        if daytime_start_hour <= int(hour) <= daytime_end_hour:
            return True
        else:
            return False

ny_timezone = pytz.timezone('America/New_York')
london_timezone = pytz.timezone('Europe/London')
tokyo_timezone = pytz.timezone('Asia/Tokyo')
au_timezone = pytz.timezone('Australia/Sydney')
dubai_timezone = pytz.timezone('Asia/Dubai')
la_timezone = pytz.timezone('America/Los_Angeles')
cn_timezone = pytz.timezone('Asia/Shanghai')
paris_timezone = pytz.timezone('Europe/Paris')
in_timezone = pytz.timezone('Asia/Kolkata')
auck_timezone = pytz.timezone('Pacific/Auckland')
bang_timezone = pytz.timezone('Asia/Bangkok')
istan_timezone = pytz.timezone('Europe/Istanbul')

counter = 0

if settings['display_pm'] and settings['display_seconds']:
    x_offset = 72
elif settings['display_pm'] and not settings['display_seconds']:
    x_offset = 87
elif not settings['display_pm'] and settings['display_seconds']:
    x_offset = 87
else:
    x_offset = 102

while True:
    if 0 <= counter <= 5:
        canvas.Clear()
        #NEW YORK
        ny_time = getTimes(ny_timezone)
        #LONDON
        london_time = getTimes(london_timezone)
        #TOKYO TIME
        tokyo_time = getTimes(tokyo_timezone)

        ny_color = time_colors['day'] if isDaytime(ny_time) else time_colors['night']
        london_color = time_colors['day'] if isDaytime(london_time) else time_colors['night']
        tokyo_color = time_colors['day'] if isDaytime(tokyo_time) else time_colors['night']

        if not settings['display_pm']:
            ny_time = ny_time.replace("PM", "").replace("AM", "")
            london_time = london_time.replace("PM", "").replace("AM", "")
            tokyo_time = tokyo_time.replace("PM", "").replace("AM", "")
        
        graphics.DrawText(canvas, font, 2, 8, color, 'NEW YORK')
        graphics.DrawText(canvas, font, x_offset, 8, ny_color, ny_time)
        graphics.DrawLine(canvas, 0, 10, 128, 10, line_c)
        graphics.DrawText(canvas, font, 2, 19, color, 'LONDON')
        graphics.DrawText(canvas, font, x_offset, 19, london_color, london_time)
        graphics.DrawLine(canvas, 0, 21, 128, 21, line_c)
        graphics.DrawText(canvas, font, 2, 30, color, 'TOKYO')
        graphics.DrawText(canvas, font, x_offset, 30, tokyo_color, tokyo_time)
        canvas = matrix.SwapOnVSync(canvas)

        counter += 1
#        print("NY:", ny_time, "LONDON:", london_time, 'TOKYO:', tokyo_time)

    elif 6 <= counter <= 11:
        canvas.Clear()
        #SYDNEY
        au_time = getTimes(au_timezone)
        #DUBAI
        dubai_time = getTimes(dubai_timezone)
        #LOS ANGELES
        la_time = getTimes(la_timezone)
        
        au_color = time_colors['day'] if isDaytime(au_time) else time_colors['night']
        dubai_color = time_colors['day'] if isDaytime(dubai_time) else time_colors['night']
        la_color = time_colors['day'] if isDaytime(la_time) else time_colors['night']

        if not settings['display_pm']:
            au_time = au_time.replace("PM", "").replace("AM", "")
            dubai_time = dubai_time.replace("PM", "").replace("AM", "")
            la_time = la_time.replace("PM", "").replace("AM", "")
        
        graphics.DrawText(canvas, font, x_offset, 8, au_color, au_time)
        graphics.DrawText(canvas, font, 2, 8, color, 'SYDNEY')
        graphics.DrawLine(canvas, 0, 10, 128, 10, line_c)
        graphics.DrawText(canvas, font, x_offset, 19, dubai_color, dubai_time)
        graphics.DrawText(canvas, font, 2, 19, color, 'DUBAI')
        graphics.DrawLine(canvas, 0, 21, 128, 21, line_c)
        graphics.DrawText(canvas, font, x_offset, 30, la_color, la_time)
        graphics.DrawText(canvas, font, 2, 30, color, 'LOS ANGELES')
        canvas = matrix.SwapOnVSync(canvas)

        counter += 1
#        print('DUBAI:', dubai_time, 'AU:', au_time, "LA:", la_time)

    elif 12 <= counter <= 17:
        canvas.Clear()
        #SHANGHAI
        cn_time = getTimes(cn_timezone)
        #PARIS
        paris_time = getTimes(paris_timezone)
        #MUMBAI
        in_time = getTimes(in_timezone)

        cn_color = time_colors['day'] if isDaytime(cn_time) else time_colors['night']
        paris_color = time_colors['day'] if isDaytime(paris_time) else time_colors['night']
        in_color = time_colors['day'] if isDaytime(in_time) else time_colors['night']

        if not settings['display_pm']:
            cn_time = cn_time.replace("PM", "").replace("AM", "")
            paris_time = paris_time.replace("PM", "").replace("AM", "")
            in_time = in_time.replace("PM", "").replace("AM", "")
        
        graphics.DrawText(canvas, font, x_offset, 8, cn_color, cn_time)
        graphics.DrawText(canvas, font, 2, 8, color, 'SHANGHAI')
        graphics.DrawText(canvas, font, x_offset, 19, paris_color, paris_time)
        graphics.DrawLine(canvas, 0, 10, 128, 10, line_c)
        graphics.DrawText(canvas, font, 2, 19, color, 'PARIS')
        graphics.DrawText(canvas, font, x_offset, 30, in_color, in_time)
        graphics.DrawLine(canvas, 0, 21, 128, 21, line_c)
        graphics.DrawText(canvas, font, 2, 30, color, 'MUMBAI')
        canvas = matrix.SwapOnVSync(canvas)

        counter += 1
 #       print("CN:", cn_time,"PARIS:", paris_time,"MUMBAI:", in_time)
    elif 18 <= counter <= 23:
        canvas.Clear()
        #SHANGHAI
        auck_time = getTimes(auck_timezone)
        #PARIS
        bang_time = getTimes(bang_timezone)
        #MUMBAI
        istan_time = getTimes(istan_timezone)

        auck_color = time_colors['day'] if isDaytime(auck_time) else time_colors['night']
        bang_color = time_colors['day'] if isDaytime(bang_time) else time_colors['night']
        istan_color = time_colors['day'] if isDaytime(istan_time) else time_colors['night']

        if not settings['display_pm']:
            auck_time = auck_time.replace("PM", "").replace("AM", "")
            bang_time = bang_time.replace("PM", "").replace("AM", "")
            istan_time = istan_time.replace("PM", "").replace("AM", "")
        
        graphics.DrawText(canvas, font, x_offset, 8, auck_color, auck_time)
        graphics.DrawText(canvas, font, 2, 8, color, 'AUCKLAND')
        graphics.DrawText(canvas, font, x_offset, 19, bang_color, bang_time)
        graphics.DrawLine(canvas, 0, 10, 128, 10, line_c)
        graphics.DrawText(canvas, font, 2, 19, color, 'BANGKOK')
        graphics.DrawText(canvas, font, x_offset, 30, istan_color, istan_time)
        graphics.DrawLine(canvas, 0, 21, 128, 21, line_c)
        graphics.DrawText(canvas, font, 2, 30, color, 'ISTANBUL')
        canvas = matrix.SwapOnVSync(canvas)

        counter += 1
 #       print("CN:", cn_time,"PARIS:", paris_time,"MUMBAI:", in_time)
        if counter == 24:
            counter = 0

    time.sleep(1)



