import type { VignetteEffect } from "postprocessing";

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

/**
 * [Vignette](https://engine.needle.tools/docs/api/Vignette) darkens the edges of the rendered scene to draw attention to the center.  
 * This effect simulates the natural vignetting that occurs in photography and cinematography, where the corners of an image are darker than the center.  
 * It can be used to enhance the visual focus on the main subject of the scene and create a more immersive viewing experience.
 * @summary Vignette Post-Processing Effect
 * @category Effects
 * @group Components
 */
export class Vignette extends PostProcessingEffect {
    get typeName(): string {
        return "Vignette";
    }

    @serializable(VolumeParameter)
    color: VolumeParameter = new VolumeParameter({ r: 0, g: 0, b: 0, a: 1 });

    @serializable(VolumeParameter)
    intensity: VolumeParameter = new VolumeParameter(0);

    @serializable(VolumeParameter)
    center: VolumeParameter = new VolumeParameter({ x: 0.5, y: 0.5 });

    init(){
        this.color.defaultValue = { r: 0, g: 0, b: 0, a: 1 };
        this.intensity.defaultValue = 0;
        this.center.defaultValue = { x: 0.5, y: 0.5 };
    }

    onCreateEffect(): EffectProviderResult {
        // https://github.com/pmndrs/postprocessing/blob/f8ed90635ee6710744cc0f38811fc00ce873a450/src/effects/VignetteEffect.js
        const vignette = new MODULES.POSTPROCESSING.MODULE.VignetteEffect();

        this.intensity.onValueChanged = v => {
            vignette.offset = v;
            this.updateDarkness(vignette);
        }
        this.color.onValueChanged = _ => {
            this.updateDarkness(vignette);
        };
        // this.center.onValueChanged = v => {
        //     console.log(v);
        //     vignette.offset = v.x;
        // };

        return vignette;
    }

    private updateDarkness(effect: VignetteEffect) {
        // const col = this.color.value;
        // const colval = 1 - (col.r + col.g + col.b + col.a) / 4;
        const val = this.intensity.value;
        effect.darkness = val;
    }

}
registerCustomEffectType("Vignette", Vignette);