import { SignalBinding } from "../../../../../../core/events/signal/SignalBinding.js";
import { PointLight } from "../../../../render/forward_plus/model/PointLight.js";
import { LightBinding } from "../LightBinding.js";

export class FPLightBinding extends LightBinding {
    constructor() {
        super();

        /**
         *
         * @type {PointLight|null}
         * @private
         */
        this.__light = null;

        /**
         *
         * @type {SignalBinding[]}
         */
        this.bindings = [];
    }

    /**
     * @param {LightContext} ctx
     * @return {ForwardPlusRenderingPlugin}
     * @private
     */
    getPlugin(ctx) {
        return ctx.system.__plugin.getValue();
    }

    #updateDistance() {
        this.__light.radius.set(this.scaled_distance);
    }

    link(ctx) {
        /**
         *
         * @type {ForwardPlusRenderingPlugin}
         */
        const fp = this.getPlugin(ctx);

        const lightManager = fp.getLightManager();

        const pl = new PointLight();

        const cLight = this.__c_light;
        const cTransform = this.__c_transform;

        this.bindings.push(
            new SignalBinding(cLight.distance.onChanged, this.#updateDistance, this),
            new SignalBinding(cTransform.scale.onChanged, this.#updateDistance, this)
        );

        pl.intensity = cLight.intensity;
        pl.color = cLight.color;

        pl.position = cTransform.position;

        /**
         *
         * @type {PointLight}
         * @private
         */
        cLight.__fp_light = pl;

        this.__light = pl;

        this.#updateDistance();

        lightManager.addLight(pl);

        for (let i = 0; i < this.bindings.length; i++) {
            this.bindings[i].link();
        }
    }

    unlink(ctx) {
        /**
         *
         * @type {ForwardPlusRenderingPlugin}
         */
        const fp = this.getPlugin(ctx);

        const lightManager = fp.getLightManager();

        lightManager.removeLight(this.__light);

        for (let i = 0; i < this.bindings.length; i++) {
            this.bindings[i].unlink();
        }
        this.bindings.splice(0, this.bindings.length);
    }
}
