import { loading_screen } from "./loading-screen.js";

export class screen {
    #root;
    #view;
    #loader;

    constructor(root, loader) {
        this.#root = root;
        this.#loader = loader;
    }

    get loader() {
        return this.#loader;
    }

    get root() {
        return this.#root;
    }

    get view() {
        return this.#view;
    }

    get #loading() {
        return new loading_screen();
    }

    #change_view(target) {
        if (this.#view !== undefined) {
            this.#view.destroy();
        }

        this.#view = target;
        const content = this.#view.show();

        if (!(content instanceof HTMLElement)) {
            throw new TypeError("View show not return HTML Element.");
        }

        while (this.root.lastChild) {
            this.root.lastChild.remove();
        }

        this.root.appendChild(content);
        this.#loading.hide();
    }

    set view(which) {
        if (typeof(which) !== "function") {
            throw new Error("Target must be class extends view.");
        }

        const target = new which(this);

        if (this.#loading.visible) {
            this.#change_view(target)
            return;
        }

        this.#loading.show();

        setTimeout(() => {
            this.#change_view(target);
        }, this.#loading.time);
    }
}