#PyFolderPicker.py
import flet as ft
import glob

def main(page: ft.Page):
    
    page.title = 'PyFolderPicker V1.2'
    
    def escapeBraceForGlob(str):
        #convert [ -> [[]  ,  ] -> []]
        newStr = str.replace('[','\\[').replace(']','\\]')
        newStr = newStr.replace('\\[','[[]').replace('\\]','[]]')
        return newStr
    
    def tab_change(e):
        page.title = tabs_control.tabs[tabs_control.selected_index].tooltip
        page.update()

    def picker(e: ft.FilePickerResultEvent):
        folder.value = e.path
        pas15 = folder.value[:15]
        a = list(folder.value + '\*.*'); a.insert(3, '\\'); s = ''.join(a)
        grf = [ft.Image(src=x) for x in glob.glob(escapeBraceForGlob(s))] 
        r = int(dropdown.value)
        tabs_control.tabs[tabs_control.selected_index].content = ft.GridView(grf, runs_count = r, expand = True)
        tabs_control.tabs[tabs_control.selected_index].text = pas15
        tabs_control.tabs[tabs_control.selected_index].tooltip = folder.value
        page.title = folder.value
        page.update()

    def remove_tab_click(e):
        if len(tabs_control.tabs) > 0:
            tabs_control.tabs.pop(tabs_control.selected_index)
            page.update()

    def add_tab_click(e):
        folder.value = ''
        new_tab_count = len(tabs_control.tabs) + 1
        tabs_control.tabs.append(ft.Tab(text=f'タブ {new_tab_count}',content = ft.Row([dropdown, button, folder])))
        tabs_control.selected_index = new_tab_count - 1
        page.update()
        
    ###############################################################################################################        
    dropdown = ft.Dropdown(tooltip = '列数指定',value='5', options=[
        ft.dropdown.Option('5'), ft.dropdown.Option('10'), ft.dropdown.Option('15'), ft.dropdown.Option('20')])
    
    pick = ft.FilePicker(on_result = picker); page.overlay.append(pick)
    folder = ft.TextField(tooltip = '選択されたフォルダ')
    button = ft.IconButton(tooltip = 'フォルダ選択', icon = ft.Icons.FOLDER,
        on_click = lambda _: pick.get_directory_path(dialog_title = 'select'))
    
    tabs_control = ft.Tabs(
        selected_index=0,
        on_change = tab_change,
        tabs=[ft.Tab(text="初期タブ", content=ft.Text("これは最初のタブです"))],
        expand=1
    )
    
    add_button = ft.ElevatedButton("タブを増やす", on_click=add_tab_click)
    pop_button = ft.ElevatedButton("タブを減らす", on_click=remove_tab_click)
    page.add(ft.Row([add_button, pop_button]), tabs_control)

ft.app(target=main)    