from datetime import datetime

from nicegui import ui, app

from users import *
from definitions import *
from calendar import monthrange

import hashlib
import calendar
import locale

locale.setlocale(locale.LC_ALL, '')

class pageheader:
    def __init__(self, heading):
        self.heading = heading

        ui.markdown(f"##{app_title} {app_version}")
        ui.markdown(f"###{self.heading}")

class ValueBinder:
    def __init__(self):
        self.value = ""

def hash_password(password):
    return hashlib.sha256(bytes(password, 'utf-8')).hexdigest()

class login_mask:
    def __init__(self, target="/"):
        data = load_adminsettings()
        self.target = target

        def login():
            nonlocal data

            if username.value == data["admin_user"]:
                if hash_password(password.value) == data["admin_password"]:
                    app.storage.user['admin_authenticated'] = True
                    ui.navigate.to("/admin")
                else:
                    ui.notify("Login fehlgeschlagen")
            else:
                userlist = list_users()

                if username.value in userlist:
                    current_user = user(username.value)

                    if hash_password(password.value) == current_user.password:
                        app.storage.user['active_user'] = current_user.username
                        ui.navigate.to(self.target)
                    else:
                        ui.notify("Login fehlgeschlagen")
                else:
                    ui.notify("Login fehlgeschlagen")

        # ui.markdown(f"## {app_title} {app_version}")
        # ui.markdown("Bitte einloggen")

        pageheader("Bitte einloggen:")

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

            ui.space()
            with ui.grid(columns=2):
                ui.markdown("Benutzer:")
                username = ui.input('Benutzername')
                ui.markdown("Passwort:")
                password = ui.input('Passwort', password=True).on('keypress.enter', login)
                ui.button(text="Login", on_click=lambda: login())
            ui.space()

def convert_seconds_to_hours(seconds):
    if seconds < 0:
        sign = "-"
        seconds = seconds * (-1)
    else:
        sign = ""
    hours = seconds // 3600
    remaining_seconds = seconds - hours * 3600
    minutes = remaining_seconds // 60
    remaining_seconds = remaining_seconds - minutes * 60
    if remaining_seconds > 0 and sign != "-":
        minutes = minutes + 1
        if minutes == 60:
            hours = hours + 1
            minutes = 0
    if hours < 10:
        hours = "0" + str(hours)
    else:
        hours = str(hours)
    if minutes < 10:
        minutes = "0" + str(minutes)
    else:
        minutes = str(minutes)

    if sign == "-":
        return f"-{hours}:{minutes}"
    else:
        return f"{hours}:{minutes}"

def login_is_valid(user = -1):

    if user == -1:
        try:
            app.storage.user['active_user']
            return True
        except:
            return False
    else:
        try:
            if app.storage.user['active_user'] == user:
                return True
            else:
                return False
        except:
            return False

