import { login_manager } from "./login_manager.js";
import { login_prompt } from "./login_prompt.js";
import { product_adder } from "./product_adder.js";
import { import_products } from "./import_products.js";

export class login_bar {
    #manager;

    constructor(target) {
        this.#manager = new login_manager();

        if (!this.#manager.logged_in) {
            this.#not_logged(target);
            return;
        }

        this.#logged(target);
    }

    #not_login_propertly() {
        this.#manager.logout();
        location.reload();
    }

    async #logged(target) {
        const user = await this.#manager.get_user();

        if (user === null) {
            this.#not_login_propertly();
        }   

        const info_icon = document.createElement("span");
        info_icon.classList.add("icon");
        info_icon.classList.add("material-icons");
        info_icon.innerText = "account_circle";

        const info_content = document.createElement("span");
        info_content.innerText = user.nick;

        const info = document.createElement("p");
        info.classList.add("login-info");
        info.appendChild(info_icon);
        info.appendChild(info_content);
        target.appendChild(info);

        const logout_button = document.createElement("button");
        logout_button.innerText = "logout";
        logout_button.classList.add("logout-button");
        logout_button.classList.add("material-icons");
        target.appendChild(logout_button);

        const add_product_button = document.createElement("button");
        add_product_button.innerText = "add";
        add_product_button.classList.add("add-product-button");
        add_product_button.classList.add("material-icons");
        target.appendChild(add_product_button);

        const import_products_button = document.createElement("button");
        import_products_button.innerText = "dataset_linked";
        import_products_button.classList.add("material-icons");
        import_products_button.classList.add("import-products-button");
        target.appendChild(import_products_button);

        add_product_button.addEventListener("click", () => {
            new product_adder().show();
        });

        import_products_button.addEventListener("click", () => {
            new import_products().show();
        });

        logout_button.addEventListener("click", () => {
            this.#manager.logout();
            location.reload();
        });
    }

    #not_logged(target) {
        const login_button = document.createElement("button");
        login_button.innerText = "account_circle";
        login_button.classList.add("login-button");
        login_button.classList.add("material-icons");
        target.appendChild(login_button);

        new login_prompt(login_button);
    }
}
