import {
    DepthFormat,
    DepthTexture,
    FloatType,
    NearestFilter,
    sRGBEncoding,
    Vector2,
    WebGLMultisampleRenderTarget
} from "three";
import { GL_RGBFormat } from "../../../texture/GL_RGBFormat.js";
import { FrameBuffer } from "../FrameBuffer.js";

/**
 *
 * @param {WebGL2RenderingContext|WebGLRenderingContext} context
 * @returns {boolean}
 */
function isWebGL2(context) {
    if (WebGL2RenderingContext === undefined) {
        return false;
    }

    if (context instanceof WebGL2RenderingContext) {
        return true;
    }

    return false;
}

export class ColorAndDepthFrameBuffer extends FrameBuffer {
    initialize(renderer) {

        //attach depth buffer
        if (!isWebGL2(renderer.getContext()) && !renderer.extensions.get('WEBGL_depth_texture')) {
            //missing depth texture extension
            throw new Error(`renderer does not support required 'WEBGL_depth_texture' extension`);
        }

        const size = new Vector2();

        renderer.getSize(size);

        const target = new WebGLMultisampleRenderTarget(size.x, size.y, { ignoreDepth: false });

        target.texture.format = GL_RGBFormat; // note, three.js required RGBA render texture, even though RGB would do here
        target.texture.minFilter = NearestFilter;
        target.texture.magFilter = NearestFilter;
        target.texture.generateMipmaps = false;
        target.texture.encoding = sRGBEncoding;

        target.stencilBuffer = false;
        target.depthBuffer = true;

        target.depthTexture = new DepthTexture();
        target.depthTexture.format = DepthFormat;
        target.depthTexture.type = FloatType;
        target.depthTexture.generateMipmaps = false;
        target.depthTexture.internalFormat = 'DEPTH_COMPONENT32F';

        this.renderTarget = target;
    }
}
