import PySimpleGUI as sg
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont, ImageOps
from io import BytesIO

# Globals 


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.
    """
    # render text
    text = Image.new(mode="RGBA", size=(1280,720))
    font1 = ImageFont.truetype('tahomabd.ttf', 50)
    font2 = ImageFont.truetype('tahomabd.ttf', 38)
    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))
    font1 = ImageFont.truetype('tahomabd.ttf', 50)
    font2 = ImageFont.truetype('tahomabd.ttf', 38)
    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 = 'Bible Stduy Wednesday June 1st, 2022'
    image_path = 'blank_title.png'
    original = Image.open(image_path)
    image = update_image(original, title, subtitle)
    thumbnail = update_thumbnail(image)

    layout = build_layout(title, subtitle, thumbnail)
    window = sg.Window('Harvest Christian Assembly Message Title', layout)

    # 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 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())


        if event == "-SAVE-":
            save_path = 'Title.png'
            image.save(save_path, 'PNG')

    window.close()

if __name__ == "__main__":
    main()
