const Scene = require('Scene');
const Options = require('Options');
const Image = require('Image');
const Texture = require('Texture');
const Mdl_function_call = require('Mdl_function_call');

module.exports.command = {
    name: 'tutorial_add_hdri',
    description: 'Adds a HDRI lighting environment to an existing scene.',
    groups: ['tutorial', 'javascript'],
    arguments: {
        scene_name: {
            description: 'The name of the existing scene to add the HDRI lighting to.',
            type: 'String'
        },
        hdri_filename: {
            description: 'The filename of the HDRI image to use for the environment.',
            type: 'String'
        },
        hdri_intensity: {
            description: 'Multiplier for the values within the HDRI image.',
            type: 'Float32',
            default: 1.0
        }
    },
    execute: function({scene_name, hdri_filename, hdri_intensity}) {
        // Fetch the existing scene data to work with
        const scene = new Scene(scene_name);
        const options = scene.options;

        // Create an Image element which will hold the image data for the environment
        let hdri_image = new Image(`${scene.name}_environment_image`, true);

        // Load the actual image data from the chosen file into the image
        hdri_image.filename = hdri_filename;

        // We can't use the image directly so need to make a texture to reference it
        let hdri_texture = new Texture(`${scene.name}_environment_texture`, true);

        // Now we can set the image of the texture to our loaded HDRI image
        hdri_texture.image = hdri_image;

        // Import base.mdl to access environment_spherical MDL function
        // NOTE: This file doesn't actually exist, it is built in
        Scene.import_elements('${shader}/base.mdl');

        // Create an MDL function to lookup the texture as an environment
        let environment = Mdl_function_call.create(`${scene.name}_environment_function`,
            'mdl::base::environment_spherical', {
                texture: hdri_texture
            }
        );

        // Set the environment_function attribute on the options to actually use the environment
        options.attributes.set('environment_function', environment.name, 'Ref');

        // Set the environment_function_intensity attribute on the options to increase brightness
        options.attributes.set('environment_function_intensity', hdri_intensity, 'Float32');
    }
};
