import flet as ft
from utils import views_handler
from modules.settings.functions import config
from utils import checkInternet


def main(page: ft.Page):
    page.title = 'BillPay'
    print('Initial route:', page.route)
    config.save('general', 'ignore_network', '0')

    def route_change(e: ft.ControlEvent):
        print('Route change:', e.route)
        page.views.clear()
        page.views.append(
            views_handler(page)[page.route],
        )
        page.update()
        if not config.getint('general', 'ignore_network') and not checkInternet():
            dlg = ft.CupertinoActionSheet(
                title=ft.Text('No Internet'),
                message=ft.Text(
                    'Please check your network connectivity and try again',
                ),
                cancel=ft.CupertinoActionSheetAction(
                    content=ft.Text('Okay'),
                    on_click=lambda _: (
                        page.close_bottom_sheet() if checkInternet(
                        ) else None, page.update(), None if e.route == '/' else page.go('/'),
                    ),
                ),
                actions=[
                    ft.CupertinoActionSheetAction(
                        content=ft.Text('Ignore Completely'),
                        is_destructive_action=True,
                        on_click=lambda e: (
                            page.close_bottom_sheet(), config.save(
                                'general', 'ignore_network', '1',
                            ),
                        ),
                    ),
                ],
            )
            page.show_bottom_sheet(ft.CupertinoBottomSheet(dlg))

    def view_pop(e: ft.ControlEvent):
        print('View pop:', e.view)
        page.views.pop()
        top_view = page.views[-1]
        page.go(top_view.route)

    if config.get('general', 'theme') == 'dark':
        page.theme_mode = ft.ThemeMode.DARK
    else:
        page.theme_mode = ft.ThemeMode.LIGHT
    page.on_route_change = route_change
    page.on_view_pop = view_pop
    page.go(page.route)


ft.app(target=main, assets_dir='assets')