'use strict';

const prefabs = require("bnb_js/prefabs");

class Foreground extends prefabs.Base {
    constructor() {
        super();
        const assets = bnb.scene.getAssetManager();
        const materialName = `shaders/foreground`;
        this._material = assets.findMaterial(materialName);
        if (!this._material) {
            bnb.log(`[WARN] Unable to find material "${materialName}"`);
            return;
        }
        this._foreground_texture = assets.findImage("foreground_texture")?.asTexture();
        this._foreground_video = assets.findImage("foreground_video")?.asVideo();
        this._foreground_input_mask = this._material.findParameter("foreground_input_mask");
        this._foreground_rotation = this._material.findParameter("foreground_rotation");
    }

    /** Set foreground texture */
    filename(filename) {
        if (is_video(filename)) {
            this._foreground_video.load(filename, (success) => {
                if (success) {
                    this._foreground_video.asMedia().setLooped(true);
                    this._foreground_video.asMedia().play();
                    this._foreground_input_mask.setVector4(new bnb.Vec4(0.0, 1.0, 0.0, 0.0));
                }
            });
        } else {
            this._foreground_texture.load(filename);
            this._foreground_input_mask.setVector4(new bnb.Vec4(1.0, 0.0, 0.0, 0.0));
        }

        return this;
    }

    /**
     * @param blending_mode String; one of "off", "alpha", "premul_alpha",
     * "alpha_rgba", "screen", "add", "multiply", "min", "max"
     */
    blending(blending_mode) {
        blending_mode = blending_mode.toUpperCase();

        if (!(blending_mode in bnb.BlendingMode)) {
            throw new Error(`Unknown blending_mode ${blending_mode}`);
        }
        let state = this._material.getState();
        state.blending = bnb.BlendingMode[blending_mode];
        this._material.setState(state);
    }

    rotation(angle) {
        this._foreground_rotation.setVector4(new bnb.Vec4(angle, 0.0, 0.0, 0.0));
    }

    /** Resets any settings applied */
    clear() {
        this.filename("");
        this.blending("alpha");
        this.rotation(0.0);
        this._foreground_input_mask.setVector4(new bnb.Vec4(0.0, 0.0, 0.0, 0.0));
    }
}

exports = {
    Foreground
}

function is_video(filename)
{
    var extension = filename.split('.').pop();
    return (['mp4', 'avi', 'flv', 'mkv', 'mov', 'mts', 'webm', 'wmv', 'gif'].indexOf(extension) > -1);
}
