import type { PixelationEffect as PixelationEffectPP } from "postprocessing";

import { MODULES } from "../../../engine/engine_modules.js";
import { serializable } from "../../../engine/engine_serialization.js";
import { getParam } from "../../../engine/engine_utils.js";
import { type EffectProviderResult, PostProcessingEffect } from "../PostProcessingEffect.js";
import { VolumeParameter } from "../VolumeParameter.js";
import { registerCustomEffectType } from "../VolumeProfile.js";

const debug = getParam("debugpost");

/**
 * [PixelationEffect](https://engine.needle.tools/docs/api/PixelationEffect) Pixelation effect simulates a pixelated look by enlarging pixels in the rendered scene.  
 * This effect can be used to achieve a retro or stylized visual aesthetic, reminiscent of early video games or low-resolution graphics.
 * @summary Pixelation Post-Processing Effect
 * @category Effects
 * @group Components
 */
export class PixelationEffect extends PostProcessingEffect {
    get typeName(): string {
        return "PixelationEffect";
    }

    @serializable(VolumeParameter)
    readonly granularity: VolumeParameter = new VolumeParameter(10);

    private _effect: PixelationEffectPP | null = null;
    private _lastDpr: number = 0;

    onCreateEffect(): EffectProviderResult {

        const effect = new MODULES.POSTPROCESSING.MODULE.PixelationEffect();
        this._effect = effect;

        const dpr = this.context.renderer.getPixelRatio();
        this._lastDpr = dpr;
        effect.granularity = this.granularity.value * dpr;

        this.granularity.onValueChanged = v => {
            const dpr = this.context.renderer.getPixelRatio();
            effect.granularity = v * dpr;
            if (debug) console.debug(`[PixelationEffect] granularity changed: raw=${v}, dpr=${dpr}, effective=${effect.granularity}`);
        }

        return effect;
    }

    update() {
        if (!this._effect) return;
        const dpr = this.context.renderer.getPixelRatio();
        if (dpr !== this._lastDpr) {
            this._lastDpr = dpr;
            this._effect.granularity = this.granularity.value * dpr;
            if (debug) console.debug(`[PixelationEffect] DPR changed to ${dpr}, updating granularity: raw=${this.granularity.value}, effective=${this._effect.granularity}`);
        }
    }

}
registerCustomEffectType("PixelationEffect", PixelationEffect);
