const Scene = require('Scene');
const Group = require('Group');
const Instance = require('Instance');

module.exports.command = {
    name: 'tutorial_add_objects',
    description: 'Adds an object to an existing scene.',
    groups: ['tutorial', 'javascript'],
    arguments: {
        scene_name: {
            description: 'The name of the existing scene to add the sun and sky lighting to.',
            type: 'String'
        },
        filename: {
            description: 'The filename of the object to be loaded and inserted in the scene.',
            type: 'String'
        },
        options: {
            description: 'Importer options to use when loading the file.',
            type: 'Map',
            default: {}
        },
        positions: {
            description: 'Locations at which to insert the objects in the scene.',
            type: 'Array',
            default: [ { x: 0.0, y: 0.0, z: 0.0 } ]
        }
    },
    execute: function({scene_name, filename, options, positions}) {
        // Fetch the existing scene data and its root group to work with
        const scene = new Scene(scene_name);
        const rootgroup = scene.root_group;

        // Call the static import_elements method on Scene to load the file from disk
        const import_result = Scene.import_elements(filename, { importer_options: options });

        // Fetch the imported root group as we will want to instance this
        let object_group = new Group(import_result.rootgroup);

        // Loop through the provided positions and place an instance of the object there
        for (let i = 0; i < positions.length; i++) {
            // Create a new transformation matrix to move our object around
            let transform = new RS.Math.Matrix4x4();

            // Set the translation elements of the matrix to the position (inverted)
            transform.set_translation(-positions[i].x, -positions[i].y, -positions[i].z);

            // Create an instance to hold our object group so we can transform it
            let object_inst = new Instance(`${object_group.name}_inst_${i}`, true);

            // Attach the objects group to the instance
            object_inst.item = object_group;

            // Use the transform matrix we setup
            object_inst.matrix = transform;

            // Add the object to the root group of the main scene to it renders
            rootgroup.attach(object_inst);
        }
    }
};
