# Zeiterfassung
import datetime

from nicegui import ui, app

from users import *
from definitions import *
from calendar import monthrange, month_name

import hashlib
import calendar
import locale

from web_ui import *

@ui.page('/')
def homepage():
    ui.page_title(f'{app_title} {app_version}')
    if login_is_valid():

        try:
            current_user = user(app.storage.user["active_user"])
        except:
            del(app.storage.user["active_user"])
            ui.navigate.to('/')
        pageheader(f"Willkommen, {current_user.fullname}")

        today = datetime.datetime.now()

        @ui.refreshable
        def stamp_interface():

            time_so_far = current_user.get_worked_time(today.year, today.month, today.day)[0]

            def stamp_and_refresh():
                current_user.timestamp()
                stamp_interface.refresh()

            with ui.grid(columns='20% auto 20%').classes('w-full justify-center'):
                ui.space()
                with ui.grid(columns='1fr 1fr'):
                    if current_user.stamp_status() == status_in:
                        bg_color = 'green'
                    else:
                        bg_color = 'red'
                    working_hours = ui.markdown(convert_seconds_to_hours(time_so_far)).classes(f'col-span-2 rounded-3xl text-center text-white text-bold text-2xl border-4 border-gray-600 bg-{bg_color}')
                    in_button = ui.button("Einstempeln", on_click=stamp_and_refresh).classes('bg-green')
                    out_button = ui.button("Ausstempeln", on_click=stamp_and_refresh).classes('bg-red')

            def update_timer():
                time_in_total = time_so_far + int((datetime.datetime.now().timestamp() - current_user.get_worked_time(today.year, today.month, today.day)[1]))
                working_hours.set_content(convert_seconds_to_hours(time_in_total))

            working_timer = ui.timer(1.0, update_timer)
            working_timer.active = False

            if current_user.stamp_status() == status_in:
                in_button.set_enabled(False)
                out_button.set_enabled(True)
                working_timer.active = True

            else:
                in_button.set_enabled(True)
                out_button.set_enabled(False)
                working_timer.active = False

        stamp_interface()

        available_years = current_user.get_years()


        available_months = [ ]
        binder_month_button = ValueBinder()
        binder_month_button.value = False

        binder_available_years = ValueBinder()

        binder_vacation = ValueBinder
        binder_vacation.value = False

        binder_absence = ValueBinder
        binder_absence.value = False

        def enable_month():
            binder_month_button.value = True

        def update_month():
            month_dict = { }
            for i in current_user.get_months(month_year_select.value):
                month_dict[i] = month_name[i]

            month_month_select.set_options(month_dict)
            month_month_select.enable()

        with ui.grid(columns='1fr auto 1fr').classes('w-full justify-center'):

            ui.space()
            with ui.expansion("Tagesnotiz", icon='o_description'):
                with ui.grid(columns=2):
                    status_binder = ValueBinder()

                    def button_enabler():
                        if daynote.value == "":
                            status_binder.value = False
                        else:
                            status_binder.value = True
                    daynote = ui.textarea(on_change=button_enabler).classes('col-span-2')
                    try:
                        daynote.value = current_user.get_day_notes(today.year, today.month, today.day)["user"]
                    except:
                        daynote.value = ""

                    def save_note():
                        note_dict = { }
                        note_dict["user"] = daynote.value
                        current_user.write_notes(today.year, today.month, today.day, note_dict)

                    save_button = ui.button("Speichern", on_click=save_note)
                    #save_button.disable()
                    def del_text():
                        daynote.value = ""
                    delete_button = ui.button("Löschen", on_click=del_text).bind_enabled_from(status_binder, 'value')
                    #delete_button.disable()
                    status_binder.value = False

                    notes = current_user.get_day_notes(today.year, today.month, today.day)
                    try:
                        daynote.value = notes[current_user.username]
                    except:
                        pass

        ui.separator()

        with ui.grid(columns='1fr auto 1fr').classes('w-full justify-center'):
            ui.space()

            def activate_vacation():
                binder_vacation.value = True

            with ui.grid(columns='1fr 1fr'):

                ui.markdown("**Monatsübersicht:**").classes('col-span-2')

                month_year_select = ui.select(list(reversed(available_years)), label="Jahr", on_change=update_month).bind_value_to(binder_available_years, 'value')
                month_month_select = ui.select(available_months, label="Monat", on_change=enable_month)
                month_month_select.disable()

                ui.space()
                month_button = ui.button("Anzeigen", on_click=lambda: ui.navigate.to(f"/api/month/{current_user.username}/{month_year_select.value}-{month_month_select.value}", new_tab=True)).bind_enabled_from(binder_month_button, 'value')
                ui.markdown("**Urlaubsanspruch**").classes('col-span-2')
                vacation_select = ui.select(list(reversed(available_years)), on_change=activate_vacation)
                vacation_button = ui.button("Anzeigen", on_click=lambda: ui.navigate.to(f"/api/vacation/{current_user.username}/{vacation_select.value}", new_tab=True)).bind_enabled_from(binder_vacation, 'value')
                ui.markdown("**Fehlzeitenübersicht**").classes('col-span-2')
                absences_select = ui.select(list(reversed(available_years)))
                absences_button = ui.button("Anzeigen").bind_enabled_from(binder_absence, 'value')
                ui.separator().classes('col-span-2')

                def logout():
                    app.storage.user.pop("active_user", None)
                    ui.navigate.to("/")

                ui.button("Logout", on_click=logout).classes('col-span-2')
            ui.space()

    else:
        login_mask()