import { user } from "./user.js";

export class login_manager {
    get apikey() {
        return localStorage.getItem("apikey");
    }

    get logged_in() {
        return localStorage.getItem("apikey") !== null;
    }

    #create_request(data) {
        return {
            method: "POST",
            body: JSON.stringify(data),
            headers: {
                "Content-Type": "application/json"
            }
        };  
    }

    async get_user() {
        if (!this.logged_in) {
            return null;
        }

        const request_data = this.#create_request({
            apikey: this.apikey
        });

        const request = await fetch("/user", request_data);
        const response = await request.json();

        if (response.result !== "success") {
            return null;
        }

        return new user(
            response.nick,
            response.apikey
        );
    }

    async login(nick, password) { 
        const request_data = this.#create_request({
            nick: nick,
            password: password
        });

        const request = await fetch("/user/login", request_data);
        const response = await request.json();

        if (response.result !== "success") {
            return false;
        }

        localStorage.setItem("apikey", response.apikey);

        return true;
    }

    logout() {
        localStorage.removeItem("apikey");
    }
}   
