//@input Asset.ObjectPrefab planePrefab
/** @type {ObjectPrefab} */
var planePrefab = script.planePrefab;

//@input Component.DeviceTracking deviceTracking
/** @type {DeviceTracking} */
var deviceTracking = script.deviceTracking;

/** @type {PlaneObj[]} */
var planeObjs = [];

deviceTracking.worldOptions.nativePlaneTrackingType = NativePlaneTrackingType.Both;

script.createEvent("WorldTrackingPlanesAddedEvent").bind(function(eventData){

    /**
     * Array of trackedPlanes initialized that frame.
     * @type {TrackedPlane[]} 
     */
    var eventPlanes = eventData.getPlanes();

    // For each added eventPlane, instantiate prefab and parent to this sceneObject.
    for(var i = 0; i < eventPlanes.length; i++){

        var planeObj = planePrefab.instantiate(script.getSceneObject()).getComponent("ScriptComponent");
        planeObj.init(eventPlanes[i]);

        updatePlaneObject(planeObj, eventPlanes[i]);

        planeObjs.push(planeObj);
    }
});

script.createEvent("WorldTrackingPlanesRemovedEvent").bind(function(eventData){

    /**
     * Array of trackedPlanes destroyed that frame.
     * @type {TrackedPlane[]} // won't need once event is released
     */
    var eventPlanes = eventData.getPlanes();

    for(var i = 0; i < eventPlanes.length; i++){

        for(var j = 0; j < planeObjs.length; j++){

            if(eventPlanes[i].isSame(planeObjs[j].getTrackedPlane())){
                planeObjs[j].sceneObject.destroy(); // Destroy the scene object first
                delete planeObjs[j]; // Delete the object
                planeObjs.splice(j, 1); // Splice the index out of the array
            }
        }
    }
});

/**
 * Update plane object transforms.
 * @param {PlaneObj} planeObj 
 * @param {TrackedPlane} eventPlane 
 */
function updatePlaneObject(planeObj, eventPlane){
    planeObj.getTransform().setWorldTransform(eventPlane.transform);

    // Scale the child mesh/collider object so that it doesn't scale the text
    var scale = eventPlane.size; // The size of the detected plane: width, 0, depth
    scale.y = .5; // Give our plane objects some depth since they use box colliders
    
    planeObj.renderMeshVisual.getTransform().setLocalScale(scale);

    // Position the text at the pivot of the plane
    planeObj.text.getTransform().setLocalPosition(eventPlane.pivot);
}

script.createEvent("WorldTrackingPlanesUpdatedEvent").bind(function(eventData){

    /**
     * Array of trackedPlanes being updated that frame.
     * @type {TrackedPlane[]}
     */
    var eventPlanes = eventData.getPlanes();

    for(var i = 0; i < eventPlanes.length; i++){

        for(var j = 0; j < planeObjs.length; j++){

            if(eventPlanes[i].isSame(planeObjs[j].getTrackedPlane())){
                updatePlaneObject(planeObjs[j], eventPlanes[i]);

            }
        }
    }
});
