/*=========================================================================

   Library: iMSTK

   Copyright (c) Kitware, Inc. & Center for Modeling, Simulation,
   & Imaging in Medicine, Rensselaer Polytechnic Institute.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

=========================================================================*/

#include "imstkScene.h"
#include "imstkCamera.h"
#include "imstkCameraController.h"
#include "imstkCollidingObject.h"
#include "imstkCollisionGraph.h"
#include "imstkCollisionPair.h"
#include "imstkComputeGraph.h"
#include "imstkComputeGraphVizWriter.h"
#include "imstkDebugRenderGeometry.h"
#include "imstkDeformableObject.h"
#include "imstkDynamicObject.h"
#include "imstkFEMDeformableBodyModel.h"
#include "imstkInteractionPair.h"
#include "imstkLight.h"
#include "imstkParallelUtils.h"
#include "imstkPbdObject.h"
#include "imstkRigidBodyWorld.h"
#include "imstkSceneObject.h"
#include "imstkSceneObjectControllerBase.h"
#include "imstkSequentialComputeGraphController.h"
#include "imstkTbbComputeGraphController.h"
#include "imstkTimer.h"

namespace imstk
{
Scene::Scene(const std::string& name, std::shared_ptr<SceneConfig> config) :
    m_name(name),
    m_camera(std::make_shared<Camera>()),
    m_collisionGraph(std::make_shared<CollisionGraph>()),
    m_config(config),
    m_computeGraph(std::make_shared<ComputeGraph>("Scene_" + name + "_Source", "Scene_" + name + "_Sink")),
    benchmarkLock(std::make_shared<ParallelUtils::SpinLock>())
{
}

Scene::~Scene()
{
    // Join Camera Controllers
    for (auto camController : m_cameraControllers)
    {
        camController->end();
        m_threadMap.at(camController->getName()).join();
    }
}

bool
Scene::initialize()
{
    // Initialize all the SceneObjects
    for (auto const& it : m_sceneObjectsMap)
    {
        auto sceneObject = it.second;
        CHECK(sceneObject->initialize()) << "Error initializing scene object: " << sceneObject->getName();
    }

    // Build the compute graph
    buildComputeGraph();

    // Opportunity for external configuration
    if (m_postComputeGraphConfigureCallback != nullptr)
    {
        m_postComputeGraphConfigureCallback(this);
    }

    // Then init
    initComputeGraph();

    m_isInitialized = true;
    LOG(INFO) << "Scene '" << this->getName() << "' initialized!";
    return true;
}

void
Scene::buildComputeGraph()
{
    // Configures the edges/flow of the graph

    // Clear the compute graph of all nodes/edges except source+sink
    m_computeGraph->clear();

    // Setup all SceneObject compute graphs (and segment the rigid bodies)
    std::list<std::shared_ptr<SceneObject>> rigidBodies;
    for (auto const& it : m_sceneObjectsMap)
    {
        auto sceneObject = it.second;
        if (sceneObject->getType() == SceneObject::Type::Rigid)
        {
            rigidBodies.push_back(sceneObject);
        }

        sceneObject->initGraphEdges();
    }

    // Apply all the interaction graph element operations to the SceneObject graphs
    const std::vector<std::shared_ptr<ObjectInteractionPair>>& pairs = m_collisionGraph->getInteractionPairs();
    for (size_t i = 0; i < pairs.size(); i++)
    {
        pairs[i]->modifyComputeGraph();
    }

    // Nest all the SceneObject graphs within this Scene's ComputeGraph
    for (auto const& it : m_sceneObjectsMap)
    {
        std::shared_ptr<ComputeGraph> objComputeGraph = it.second->getComputeGraph();
        if (objComputeGraph != nullptr)
        {
            // Add edges between any nodes that are marked critical and running simulatenously
            objComputeGraph = ComputeGraph::resolveCriticalNodes(objComputeGraph);
            // Sum and nest the graph
            m_computeGraph->nestGraph(objComputeGraph, m_computeGraph->getSource(), m_computeGraph->getSink());
        }
    }

    // Edge Case: Rigid bodies all have a singular update point because of how PhysX works
    // Think about generalizes these islands of interaction to Systems
    if (rigidBodies.size() > 0)
    {
        // The node that updates the rigid body system
        auto physXUpdate = m_computeGraph->addFunction("PhysXUpdate", [&]()
            {
                auto physxScene = RigidBodyWorld::getInstance()->m_Scene;
                // TODO: update the time step, split into two steps, collide and advance
                physxScene->simulate(RigidBodyWorld::getInstance()->getTimeStep());
                physxScene->fetchResults(true);
            });

        // Scene Source->physX Update->Rigid Body Update Geometry[i]
        m_computeGraph->addEdge(m_computeGraph->getSource(), physXUpdate);
        m_computeGraph->addEdge(physXUpdate, m_computeGraph->getSink());
        for (std::list<std::shared_ptr<SceneObject>>::iterator i = rigidBodies.begin(); i != rigidBodies.end(); i++)
        {
            m_computeGraph->addEdge(physXUpdate, (*i)->getUpdateGeometryNode());
        }
    }
}

void
Scene::initComputeGraph()
{
    // Pick a controller for the graph execution
    if (m_config->taskParallelizationEnabled)
    {
        m_computeGraphController = std::make_shared<TbbComputeGraphController>();
    }
    else
    {
        m_computeGraphController = std::make_shared<SequentialComputeGraphController>();
    }
    m_computeGraphController->setComputeGraph(m_computeGraph);

    m_computeGraphController->init();

    // Check if the graph is cyclic
    if (ComputeGraph::isCyclic(m_computeGraph))
    {
        ComputeGraphVizWriter writer;
        writer.setInput(m_computeGraph);
        writer.setFileName("sceneComputeGraph.svg");
        writer.write();
        LOG(FATAL) << "Scene, '" << this->getName() << "', cannot be initialized, computational graph is cyclic. Writing graph to: computeGraph.svg";
    }

    // Reduce the graph, removing nonfunctional nodes, and redundant edges
    if (m_config->graphReductionEnabled)
    {
        m_computeGraph = ComputeGraph::reduce(m_computeGraph);
    }

    // If user wants to benchmark, tell all the nodes to time themselves
    for (std::shared_ptr<ComputeNode> node : m_computeGraph->getNodes())
    {
        node->m_enableBenchmarking = m_config->benchmarkingEnabled;
    }

    // Generate unique names among the nodes
    ComputeGraph::getUniqueNames(m_computeGraph, true);
    m_nodeNamesToElapsedTimes.clear();

    if (m_config->writeComputeGraph)
    {
        ComputeGraphVizWriter writer;
        writer.setInput(m_computeGraph);
        writer.setFileName("sceneComputeGraph.svg");
        writer.write();
    }
}

void
Scene::launchModules()
{
    // Start Camera Controller (asynchronous)
    for (auto camController : m_cameraControllers)
    {
        m_threadMap[camController->getName()] = std::thread([camController] { camController->start(); });
    }
}

bool
Scene::isObjectRegistered(const std::string& sceneObjectName) const
{
    return m_sceneObjectsMap.find(sceneObjectName) != m_sceneObjectsMap.end();
}

const std::vector<std::shared_ptr<SceneObject>>
Scene::getSceneObjects() const
{
    std::vector<std::shared_ptr<SceneObject>> v;

    for (auto it : m_sceneObjectsMap)
    {
        v.push_back(it.second);
    }

    return v;
}

const std::vector<std::shared_ptr<SceneObjectControllerBase>>
Scene::getSceneObjectControllers() const
{
    return m_objectControllers;
}

std::shared_ptr<SceneObject>
Scene::getSceneObject(const std::string& sceneObjectName) const
{
    CHECK(this->isObjectRegistered(sceneObjectName))
        << "No scene object named '" << sceneObjectName
        << "' was registered in this scene.";

    return m_sceneObjectsMap.at(sceneObjectName);
}

const std::vector<std::shared_ptr<VisualModel>>
Scene::getDebugRenderModels() const
{
    std::vector<std::shared_ptr<VisualModel>> v;

    for (auto it : m_DebugRenderModelMap)
    {
        v.push_back(it.second);
    }

    return v;
}

void
Scene::addSceneObject(std::shared_ptr<SceneObject> newSceneObject)
{
    std::string newSceneObjectName = newSceneObject->getName();

    if (this->isObjectRegistered(newSceneObjectName))
    {
        LOG(WARNING) << "Can not add object: '" << newSceneObjectName
                     << "' is already registered in this scene.";
        return;
    }

    m_sceneObjectsMap[newSceneObjectName] = newSceneObject;
    LOG(INFO) << newSceneObjectName << " object added to " << m_name;
}

void
Scene::addDebugVisualModel(std::shared_ptr<VisualModel> dbgRenderModel)
{
    const std::string name = dbgRenderModel->getDebugGeometry()->getName();

    if (m_DebugRenderModelMap.find(name) != m_DebugRenderModelMap.end())
    {
        LOG(WARNING) << "Can not add debug render mdoel: '" << name
                     << "' is already registered in this scene.";
        return;
    }

    m_DebugRenderModelMap[name] = dbgRenderModel;
    LOG(INFO) << name << " debug model added to " << m_name;
}

void
Scene::removeSceneObject(const std::string& sceneObjectName)
{
    if (!this->isObjectRegistered(sceneObjectName))
    {
        LOG(WARNING) << "No object named '" << sceneObjectName
                     << "' was registered in this scene.";
        return;
    }

    m_sceneObjectsMap.erase(sceneObjectName);
    LOG(INFO) << sceneObjectName << " object removed from " << m_name;
}

bool
Scene::isLightRegistered(const std::string& lightName) const
{
    return m_lightsMap.find(lightName) != m_lightsMap.end();
}

const std::vector<std::shared_ptr<Light>>
Scene::getLights() const
{
    std::vector<std::shared_ptr<Light>> v;

    for (auto it = m_lightsMap.begin();
         it != m_lightsMap.end();
         ++it)
    {
        v.push_back(it->second);
    }

    return v;
}

std::shared_ptr<Light>
Scene::getLight(const std::string& lightName) const
{
    if (!this->isLightRegistered(lightName))
    {
        LOG(WARNING) << "No light named '" << lightName
                     << "' was registered in this scene.";
        return nullptr;
    }

    return m_lightsMap.at(lightName);
}

void
Scene::addLight(std::shared_ptr<Light> newLight)
{
    std::string newlightName = newLight->getName();

    if (this->isLightRegistered(newlightName))
    {
        LOG(WARNING) << "Can not add light: '" << newlightName
                     << "' is already registered in this scene.";
        return;
    }

    m_lightsMap[newlightName] = newLight;
    LOG(INFO) << newlightName << " light added to " << m_name;
}

void
Scene::removeLight(const std::string& lightName)
{
    if (!this->isLightRegistered(lightName))
    {
        LOG(WARNING) << "No light named '" << lightName
                     << "' was registered in this scene.";
        return;
    }

    m_lightsMap.erase(lightName);
    LOG(INFO) << lightName << " light removed from " << m_name;
}

void
Scene::setGlobalIBLProbe(std::shared_ptr<IBLProbe> newIBLProbe)
{
    m_globalIBLProbe = newIBLProbe;
}

std::shared_ptr<IBLProbe>
Scene::getGlobalIBLProbe()
{
    return m_globalIBLProbe;
}

const std::string&
Scene::getName() const
{
    return m_name;
}

std::shared_ptr<Camera>
Scene::getCamera() const
{
    return m_camera;
}

std::shared_ptr<CollisionGraph>
Scene::getCollisionGraph() const
{
    return m_collisionGraph;
}

void
Scene::addObjectController(std::shared_ptr<SceneObjectControllerBase> controller)
{
    m_objectControllers.push_back(controller);
}

void
Scene::addCameraController(std::shared_ptr<CameraController> camController)
{
    m_cameraControllers.push_back(camController);
}

void
Scene::reset()
{
    m_resetRequested = true;
}

void
Scene::resetSceneObjects()
{
    // Apply the geometry and apply maps to all the objects
    for (auto obj : this->getSceneObjects())
    {
        obj->reset();
    }

    //\todo reset the timestep to the fixed default value when paused->run or reset
}

void
Scene::advance()
{
    StopWatch wwt;
    wwt.start();

    advance(m_elapsedTime);

    m_elapsedTime = wwt.getTimeElapsed(StopWatch::TimeUnitType::seconds);
}

void
Scene::advance(const double dt)
{
    // Reset Contact forces to 0
    for (auto obj : this->getSceneObjects())
    {
        if (auto defObj = std::dynamic_pointer_cast<FeDeformableObject>(obj))
        {
            defObj->getFEMModel()->getContactForce().setConstant(0.0);
        }
        else if (auto collidingObj = std::dynamic_pointer_cast<CollidingObject>(obj))
        {
            collidingObj->resetForce();
        }
    }

    // Update objects controlled by the device controllers
    for (auto controller : this->getSceneObjectControllers())
    {
        controller->updateControlledObjects();
    }

    CollisionDetection::updateInternalOctreeAndDetectCollision();

    // Execute the computational graph
    m_computeGraphController->execute();

    // Apply updated forces on device
    for (auto controller : this->getSceneObjectControllers())
    {
        controller->applyForces();
    }

    // Set the trackers of the scene object controllers to out-of-date
    for (auto controller : this->getSceneObjectControllers())
    {
        controller->setTrackerToOutOfDate();
    }

    for (auto obj : this->getSceneObjects())
    {
        if (auto dynaObj = std::dynamic_pointer_cast<DynamicObject>(obj))
        {
            if (dynaObj->getDynamicalModel()->getTimeStepSizeType() == TimeSteppingType::RealTime)
            {
                dynaObj->getDynamicalModel()->setTimeStep(dt);
            }
        }
    }

    if (m_resetRequested)
    {
        resetSceneObjects();
        //\note May need to reset CD, CH and other components of the scene in the future
        m_resetRequested = false;
    }

    this->setFPS(1.0 / dt);

    // If benchmarking enabled, produce a time table for each step
    if (m_config->benchmarkingEnabled)
    {
        lockBenchmark();
        for (std::shared_ptr<ComputeNode> node : m_computeGraph->getNodes())
        {
            m_nodeNamesToElapsedTimes[node->m_name] = node->m_elapsedTime;
        }
        unlockBenchmark();
    }
}

double
Scene::getElapsedTime(const std::string& stepName) const
{
    if (m_nodeNamesToElapsedTimes.count(stepName) == 0)
    {
        LOG(WARNING) << "Tried to get elapsed time of nonexistent step. Is benchmarking enabled?";
        return 0.0;
    }
    else
    {
        return m_nodeNamesToElapsedTimes.at(stepName);
    }
}

void
Scene::lockBenchmark()
{
    benchmarkLock->lock();
}

void
Scene::unlockBenchmark()
{
    benchmarkLock->unlock();
}
} // imstk
