// Global ATON

import AppState from "./state.js";
import { config } from "../config.js";
import { toggleAmbientOcclusion } from "./utils/environment.js";

/**
 * @module Scene
 */

/**
 * @todo Experimental...
 * @param {THREE.Object3D} object - A THREE Object3D instance
 */
function showEdges (object) {
    const edgeMaterial = new THREE.LineBasicMaterial( { color: 0x000000 } );

    object.traverse(function(child) {
    
        if (child.isMesh) {
            let edges = new THREE.EdgesGeometry(child.geometry, 45);
            let line = new THREE.LineSegments(edges, edgeMaterial);
            child.add(line);
        
            console.log(child);
        }
    });
}

function init () {
    ATON.realize();
    ATON.UI.addBasicEvents();
    ATON.UI.init();
    // All assets for this app are stored here
    ATON.setPathCollection('/a/scaenae/assets/');
    // Initial light direction
    ATON.setMainLightDirection(new THREE.Vector3(...config.scene.initLightDir));
    ATON.toggleShadows(config.scene.shadows);
    ATON.setExposure(config.scene.initialExposure);
    // Open settings side panel when clicking on settings btn

    AppState.camera = ATON.Nav._camera;
    AppState.renderer = ATON._renderer;
    AppState.shadows = config.scene.shadows;

    ATON.Nav.setUserControl(true);
}
/**
 * @param {Object} marker - The marker object from config
 * @param {Object[]} nodes - The flat list of nodes for this scene
 */
export function openScene (marker, nodes) {
    init();
    // Filter nodes with models first
    nodes = nodes.filter(n => n.model);
    // Load 3D models and create nodes
    loadNodes(nodes);

    ATON.setMainPanorama(marker.pano);
    // TODO: hardcoded...
    AppState.initialRotation = new THREE.Vector3(...config.scene.initRotation);

    ATON.setAutoLP(config.scene.autoLP);
    AppState.lightProbe = config.scene.autoLP;
    toggleAmbientOcclusion(true);
    AppState.ambientOcclusion = true;
    AppState.root = ATON.getRootScene();
}

/**
 * 
 * @param {Object[]} nodes 
 */
function loadNodes(nodes) {
    nodes.forEach(n => {
        let node = ATON.createSceneNode(n.label);
        node.load(n.model);
        node.setRotation(...config.scene.initRotation);

        // Apply any transparency before attaching to scene
        if (n.opacity !== undefined && n.opacity !== null) {
            node.setMaterial(new THREE.MeshPhongMaterial({
                transparent: true,
                opacity: n.opacity,
                color: '#fff'
            }));
        }

        node.attachToRoot();

        if (n.isMain) {
            AppState.mainNodeId = n.label;
            // ATON.Node.getBound() returns a THREE.Sphere object
            AppState.clipping.boundingSphere = node.getBound();
        }

        AppState.nodes.push({id: n.label, active: true});
    });
    
    if (!AppState.clipping.boundingSphere) {
        console.error("No bounding sphere computed, clipping will fail. Ensure one node has 'isMain: true'.");
    }
}
