import { view } from "./view";
import { cx_ui } from "./cx-ui.js";
import { selector } from "./selector.js";
import { phrase } from "./phrase.js";
import { space_scene } from "./space-scene.js";
import { controler } from "./controler.js";

export class space extends view {
    #canvas;
    #context;
    #scene;
    #on_resize;
    #mouse;

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

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

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

    #init_canvas() {
        this.#context = this.canvas.getContext("webgl2");
        this.#context = this.#context || this.canvas.getContext("webgl");

        if (this.#context) {
            return;
        }

        throw new MediaError("WebGL is not supported by browser");
    }

    update_size() {
        this.#scene.update_size(window.innerWidth, window.innerHeight);
    }

    show() {
        const ui = cx_ui.div("ui");
        const render = cx_ui.div("render");

        const back = new phrase("selector.return");
        const return_button = cx_ui.push("return", back, () => {
            this.manager.view = selector;
        });

        this.#canvas = cx_ui.canvas("space-render");
        this.#mouse = new controler();

        ui.appendChild(return_button);
        render.appendChild(this.canvas);

        try {
            this.#init_canvas();
            this.#scene = new space_scene(this);
            this.update_size();
            this.#scene.start();
        } catch (fail) {
            const error = cx_ui.div("error");
            const code = cx_ui.p("code", new phrase("error.webgl-support"));

            error.appendChild(code);
            render.appendChild(error);

            this.canvas.remove();
            console.error(fail);
        }

        this.#on_resize = () => { this.update_size(); };
        this.#mouse.enable();
        window.addEventListener("resize", this.#on_resize);

        return cx_ui.div("container", null, (container) => {
            container.appendChild(render);
            container.appendChild(ui);
        });
    }

    destroy() {
        this.#scene.stop();
        this.#mouse.clean();
        window.removeEventListener("resize", this.#on_resize);
    }
}