import os
import FreeSimpleGUI as sg
from datetime import date, timedelta
from pathlib import Path
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont, ImageOps
from io import BytesIO

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

def save_filename():
    """determin file name by platform"""
    folder = Path('C:/Users/harvest/Documents/OBS/Overlays')
    if folder.exists():
        return folder / 'Title.png'
    return Path.home() / 'Pictures' / 'Title.png'

def get_subtitle():
    """find Wednesday of the current/next week"""
    today = date.today()
    if today.weekday() > 2:
        wednesday = today + timedelta(9 - today.weekday())
    else:
        wednesday = today + timedelta(2 - today.weekday())
    return wednesday.strftime('Bible Study %A %B %#d, %Y')

def update_image(original, title, subtitle):
    """Render new title and title preview
    renders text on full sized slide
    make half sized copy for preview and fill top/bottom with white.
    """
    font1 = ImageFont.truetype(resource_path('tahomabd.ttf'), 50)
    font2 = ImageFont.truetype(resource_path('tahomabd.ttf'), 38)

    # render text
    text = Image.new(mode="RGBA", size=(1280,720))
    draw = ImageDraw.Draw(text)
    draw.text((20,520), title, font=font1, fill='white',
              stroke_width=4, stroke_fill='black', spacing=4)
    draw.text((20,588), subtitle, font=font2, fill='white',
              stroke_width=4, stroke_fill='black', spacing=4)

    # render drop dhadow
    dropshadow = Image.new(mode="RGBA", size=(1280,720))
    draw = ImageDraw.Draw(dropshadow)
    draw.text((25,525), title, font=font1, fill='black',
              stroke_width=4, stroke_fill='black', spacing=4)
    draw.text((25,593), subtitle, font=font2, fill='black',
              stroke_width=4, stroke_fill='black', spacing=4)

    # apply blur
    for i in range(6):
        dropshadow = dropshadow.filter(ImageFilter.BLUR)

    # make dropdhadow 10% transparent
    alpha = dropshadow.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(.9)
    dropshadow.putalpha(alpha)

    # merge dropshdow then text layer onto background
    background = Image.alpha_composite(original, dropshadow)
    background = Image.alpha_composite(background, text)
    return background

def update_thumbnail(image):
    """genreate thumbnail from original image"""
    """454-720 scales to 227-360"""
    scaled = image.resize((720, 360))
    # white = (255, 255, 255, 255)
    # ImageDraw.floodfill(scaled, (5, 5), value=white)
    # ImageDraw.floodfill(scaled, (5, 355), value=white)
    thumbnail = scaled.crop((0, 255, 719, 359))
    return thumbnail


def build_layout(title, subtitle, thumbnail):
    control_col = sg.Column([
        [
            sg.Frame('Title',
                     layout = [[sg.Input(title, key = '-TITLE-',
                                         enable_events=True)]]
                    )],
        [
            sg.Frame('subtitle',
                     layout = [[sg.Input(subtitle, key = '-SUBTITLE-',
                                         enable_events=True)]]
                    )],
        [
            sg.Button('Save image', key= '-SAVE-')],
    ])

    bio = BytesIO()
    thumbnail.save(bio, format = 'PNG')
    image_col = sg.Column([[sg.Image(data=bio.getvalue(), key = '-IMAGE-')]])
    layout = [[control_col,image_col]]
    return layout

def main():
    title = 'Pastor Shane Wallis'
    subtitle = get_subtitle()
    image_path = resource_path('blank_title.png')
    original = Image.open(image_path)
    image = update_image(original, title, subtitle)
    thumbnail = update_thumbnail(image)
    icon_file=resource_path('projector.ico')
    
    layout = build_layout(title, subtitle, thumbnail)
    window = sg.Window('Harvest Christian Assembly Message Title', layout, icon=icon_file)

    # image contains the final image
    while True:
        event, values = window.read(timeout=50)
        if event == sg.WIN_CLOSED:
            break

        # if event == "-TITLE-" or event == '-SUBTITLE-':

        if event == "-SAVE-":
            if values['-TITLE-'] != title or values['-SUBTITLE-'] != subtitle:
                title = values['-TITLE-']
                subtitle = values['-SUBTITLE-']
                original = Image.open(image_path)
                image = update_image(original, title, subtitle)
                thumbnail = update_thumbnail(image)
                bio = BytesIO()
                thumbnail.save(bio, format = 'PNG')
                window['-IMAGE-'].update(data = bio.getvalue())
            save_path = save_filename()
            image.save(save_path, 'PNG')

    window.close()

if __name__ == "__main__":
    main()
