import { formscreen } from "./formscreen.js";
import { login_manager } from "./login_manager.js";

export class login_prompt extends formscreen {
    #nick;
    #password;

    constructor(target) {
        super();
        
        target.addEventListener("click", () => {
            this.show();
        });
    }

    get _name() {
        return "Login";
    }

    async _process() {
        try {
            this._info = "Processing...";
            await this.#login();
            this._success = "Logged in!";

            setTimeout(() => {
                location.reload();
            }, 250);
        } catch (error) {
            this._error = new String(error);
        }
    }

    async #login() {
        const manager = new login_manager();
        const result = await manager.login(
            this.#nick(), 
            this.#password()
        );

        if (result) {
            return;
        } 
        
        throw new Error("Can not login. Check nick and password.");
    }

    _build_form() {
        this.#nick = this._create_input(
            "nick",
            "Nick:",
            "Sample..."
        );

        this.#password = this._create_input(
            "password",
            "Password:",
            "ABCDEFGH",
            (input) => { input.type = "password"; }
        );
    }
}
