import PySimpleGUI as sg
# import PySimpleGUIWx as sg
# import PySimpleGUIQt as sg
from PIL import Image
import base64, io
from time import time

"""
    A periodic reminder that uses the System Tray.
    Will show a popup window every X minutes
    Should work with 3 of the PySimpleGUI ports - tkinter, WxPython, Qt
"""

ONE_HOUR_IN_SECONDS = 60*60
STARTING_FREQUENCY = ONE_HOUR_IN_SECONDS
POPUP_FONT = 'Helvetica 16'       # font to use in popup
POPUP_TEXT_COLOR, POPUP_BACKGROUND_COLOR = 'white', 'red'

def resize_base64_image(image64, size):
    """
    Resize a base64 image.  Good to use for Image elements, Button Images, etc.

    :param image64: The Base64 image
    :type image64: bytes
    :param size: Size to make the image in pixels (width, height)
    :type size: Tuple[int, int]
    :return: A new Base64 image
    :rtype: bytes
    """
    image_file = io.BytesIO(base64.b64decode(image64))
    img = Image.open(image_file)
    img.thumbnail(size, Image.ANTIALIAS)
    bio = io.BytesIO()
    img.save(bio, format='PNG')
    imgbytes = bio.getvalue()
    return imgbytes


def main():
    """
    Function with all the good stuff.  Creates the System Tray and processes all events
    """
    delay = frequency_in_seconds = STARTING_FREQUENCY

    tray_icon = resize_base64_image(icon, (64,64)) if sg.port == 'PySimpleGUI' else icon

    menu_def = ['UNUSED', ['Change Frequency', '---', 'Exit']]

    tray = sg.SystemTray(menu=menu_def, data_base64=tray_icon, tooltip=f'Reminder every {frequency_in_seconds/60} minutes')

    starting_seconds = time()

    while True:
        event = tray.read(timeout=delay*1000)
        if event == 'Exit':
            break

        delta_from_last = time() - starting_seconds
        if delta_from_last >= frequency_in_seconds:
            starting_seconds = time()
            delta_from_last = 0
            sg.popup_no_wait('Reminder!', f'It has been {frequency_in_seconds/60} minutes since your last reminder', background_color=POPUP_BACKGROUND_COLOR, text_color=POPUP_TEXT_COLOR, font=POPUP_FONT)

        if event == 'Change Frequency':       # Change how often a reminder should be shown
            freq = sg.popup_get_text(f'Currently you will be reminded every {frequency_in_seconds/60} minutes\n'+
                                     'Enter new frequency in minutes', 'Change Timer Frequency')
            try:
                frequency_in_seconds = int(float(freq)*60)
                starting_seconds = time()
                delta_from_last = 0
                tray.update(tooltip=f'Reminder every {frequency_in_seconds/60} minutes')
            except:
                sg.popup_error(f'Invalid value: {freq}', f'Keeping old frequency of {frequency_in_seconds/60} minutes')

        delay = frequency_in_seconds - delta_from_last
    tray.close()

if __name__ == '__main__':
    icon = \
        b'[encoded data, 22012 characters]'

    main()