# PyFletVideo.py V1.0
# flet                   0.80.0
# flet-desktop           0.80.0
# flet-video             0.80.0

import pyautogui
import flet as ft
import flet_video as ftv
import threading
import asyncio

sample_media = []

def main(page: ft.Page):
    vasionName = 'PyFletVideo V1.0'
    page.title = vasionName; page.padding = 20; page.spacing = 0 
    #page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
    
    async def play_or_pause(e: ft.Event[ft.Button]):
        await video.play_or_pause()

    def volume_change(e: ft.Event[ft.Slider]):
        video.volume = e.control.value

    def rate_change(e: ft.Event[ft.Slider]):
        video.playback_rate = e.control.value

    async def pick_files(e: ft.Event[ft.Button]):
        files = await ft.FilePicker().pick_files(allow_multiple=True)
        selected_files.value = (", ".join(map(lambda f: f.path, files)) if files else 'Cancelled!')
        video.playlist.clear()        
        await video.playlist_add(ftv.VideoMedia(selected_files.value))
        await video.next()
        video.volume = 50
        video.playback_rate = 1
        try:page.title = selected_files.value
        except: page.title = vasionName

    def rate1x():
        video.playback_rate = 1
        rate_slider.value = 1 
        
### screenshot スクリーンショットを撮って'canvas_screenshot.png'というファイル名でカレントディレクトリに保存する ################
    def save_screenshot(e):        
        def handle_close(e):            
            page.pop_dialog() # 最前面のダイアログを閉じる
            
        screenshot = pyautogui.screenshot(region =
            (int(page.window.left + 20), int(page.window.top + 30), int(page.window.width - 40), int(page.window.height - 100)))
        file_path = 'canvas_screenshot.png'
        screenshot.save(file_path)
        dlg = ft.AlertDialog(modal = True, title = ft.Text('PyFletVideo'),
            content = ft.Text(f'画像が {file_path} に保存されました。'), actions = [ft.TextButton("閉じる", on_click = handle_close)])        
        page.show_dialog(dlg)
        page.update()

### ボタン類をセット ##########################################################################################################
    shot_button = ft.Button('Screen Shot', tooltip = 'スクリーンショットを撮る', on_click = lambda e: threading.Thread(target=save_screenshot(e)).start())
    pick_button = ft.Button(content = 'Pick File', icon=ft.Icons.UPLOAD_FILE, on_click = pick_files, tooltip = 'メディアファイルを開く')
    play_button = ft.Button('Play / Pause', on_click = play_or_pause, tooltip = '再生/ポーズ')
    volume_slider = ft.Slider(min = 0, value = 50, max = 100, label = 'Volume = {value}%', divisions = 20,  width= 200, on_change = volume_change, tooltip = '音量')
    rate1x_button = ft.Button('Rate=1', on_click = rate1x, tooltip = '再生速度を標準にする')
    rate_slider = ft.Slider(min = 0.2, value = 1, max = 3.2, label = 'Playback rate = {value}X', divisions = 30, width = 200, round = 2, on_change = rate_change, tooltip = '再生速度')

    selected_files = ft.Text()
    page.add(
        ft.SafeArea(expand=True,
            content=ft.Column(expand=True,
                controls=[
                    video := ftv.Video(
                        expand=True,
                        playlist=sample_media[0:0],
                        playlist_mode=ftv.PlaylistMode.LOOP,
                        fill_color=ft.Colors.BLUE_400,
                        aspect_ratio=16 / 9,
                        volume=50,
                        autoplay=False,
                        filter_quality=ft.FilterQuality.HIGH,
                    ),
                    ft.Row(wrap=True, alignment=ft.MainAxisAlignment.CENTER,
                        controls=[pick_button, play_button, shot_button, volume_slider, rate1x_button, rate_slider]
                    )
                ]
            )
        )
    )

### アプリケーションの実行 #############################################
ft.run(main)