#
#   Copyright © 2021,2022 IsardVDI S.L.
#   Copyright © 2022 Evilham <contact@evilham.com>
#
#   This file is part of DD
#
#   DD is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or (at your
#   option) any later version.
#
#   DD is distributed in the hope that it will be useful, but WITHOUT ANY
#   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
#   FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
#   details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with DD. If not, see <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: AGPL-3.0-or-later
import os

from flask_login import LoginManager, UserMixin

from typing import TYPE_CHECKING, Dict

if TYPE_CHECKING:
    from admin.flaskapp import AdminFlaskApp

ram_users = {}

for app, app_role in [
    ("ADMINAPP", "manager"),
    ("KEYCLOAK", "admin"),
    ("WORDPRESS_MARIADB", "manager"),
]:
    k = f"{app}_USER"
    if os.environ.get(k, ""):
        pk = f"{app}_PASSWORD"
        ram_users[os.environ[k]] = {
            "id": os.environ[k],
            "password": os.environ[pk],
            "role": app_role,
        }


class User(UserMixin):
    def __init__(self, id: str, password: str, role: str, active: bool = True) -> None:
        self.id = id
        self.username = id
        self.password = password
        self.role = role
        self.active = active


def setup_auth(app: "AdminFlaskApp") -> None:
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = "login"

    @login_manager.user_loader
    def user_loader(username: str) -> User:
        u = ram_users[username]
        return User(id=u["id"], password=u["password"], role=u["role"])
