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-window");
    }

    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-prompt"),
            _("nick-sample")
        );

        this.#password = this._create_input(
            "password",
            _("password-prompt"),
            _("password-sample"),
            (input) => { input.type = "password"; }
        );
    }
}
