import {api} from "@/services/api";
import {Subject} from "rxjs";

export namespace Auth {

    let loggedIn = false
    let user = ""
    let privileges: string[] = []
    export const loggedInSubject: Subject<boolean> = new Subject<boolean>()

    export function isLoggedIn() {
        return loggedIn
    }

    export function getUser() {
        return user;
    }

    export function getPrivileges() {
        return privileges
    }

    function setToken(token: string) {
        window.localStorage.setItem("token", token)
    }

    export function getToken(): string {
        return window.localStorage.getItem("token")
    }

    export async function login(username: string, password: string): Promise<{
        success: boolean,
        token?: string
    }> {
        return api("/auth", "POST", {
            username, password
        }).then(res => res.json() as Promise<{
            success: boolean,
            token?: string
            privileges?: string[]
        }>).then(res => {
            if(res.success) {
                loggedIn = true
                user = username;
                privileges = res.privileges ?? []
                privileges.push(username)
                setToken(res.token ?? "")
                loggedInSubject.next(true)
            }
            return Promise.resolve(res)
        })
    }

    export function logout(){
        setToken("")
        loggedIn = false;
        user = "";
        privileges = []
        loggedInSubject.next(false)
    }

    export function checkForToken() {
        const token = getToken()
        if(token && token != ""){
            const payload = parseJwt(token)
            loggedIn = true
            user = payload.username
            privileges = payload.privileges
            privileges.push(user)
            loggedInSubject.next(true)
        }
    }

    function parseJwt (token) {
        var base64Url = token.split('.')[1];
        var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));

        return JSON.parse(jsonPayload);
    }

}

