/*
 *   ORXONOX - the hottest 3D action shooter ever to exist
 *                    > www.orxonox.net <
 *
 *
 *   License notice:
 *
 *   This program is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU General Public License
 *   as published by the Free Software Foundation; either version 2
 *   of the License, or (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 *   Author:
 *      Reto Grieder
 *   Co-authors:
 *      ...
 *
 */

/**
@file
@brief
    Implementation of the Game class.
*/

#include "Game.h"

#include <exception>
#include <loki/ScopeGuard.h>

#include "util/Clock.h"
#include "util/Output.h"
#include "util/Exception.h"
#include "util/Sleep.h"
#include "util/SubString.h"
#include "Core.h"
#include "commandline/CommandLineParser.h"
#include "GameConfig.h"
#include "GameMode.h"
#include "GameState.h"
#include "GraphicsManager.h"
#include "GUIManager.h"
#include "command/ConsoleCommandIncludes.h"

namespace orxonox
{
    static void stop_game()
        { Game::getInstance().stop(); }
    SetConsoleCommand("exit", &stop_game);
    static void printFPS()
        { orxout(message) << Game::getInstance().getAvgFPS() << endl; }
    SetConsoleCommand("Stats", "printFPS", &printFPS);
    static void printTickTime()
        { orxout(message) << Game::getInstance().getAvgTickTime() << endl; }
    SetConsoleCommand("Stats", "printTickTime", &printTickTime);

    std::map<std::string, GameStateInfo> Game::gameStateDeclarations_s;
    Game* Game::singletonPtr_s = nullptr;

    //! Represents one node of the game state tree.
    struct GameStateTreeNode
    {
        std::string name_;
        std::weak_ptr<GameStateTreeNode> parent_;
        std::vector<std::shared_ptr<GameStateTreeNode>> children_;
    };

    Game::Game(const std::string& cmdLine)
        : gameClock_(nullptr)
        , core_(nullptr)
        , bChangingState_(false)
        , bAbort_(false)
        , config_(nullptr)
        , destructionHelper_(this)
    {
        orxout(internal_status) << "initializing Game object..." << endl;

#ifdef ORXONOX_PLATFORM_WINDOWS
        minimumSleepTime_ = 1000/*us*/;
#else
        minimumSleepTime_ = 0/*us*/;
#endif

        // reset statistics
        this->statisticsStartTime_ = 0;
        this->statisticsTickTimes_.clear();
        this->periodTickTime_ = 0;
        this->periodTime_ = 0;
        this->avgFPS_ = 0.0f;
        this->avgTickTime_ = 0.0f;
        this->excessSleepTime_ = 0;

        // Create an empty root state
        this->declareGameState<GameState>("GameState", "emptyRootGameState", true, false);

        // Set up a basic clock to keep time
        this->gameClock_ = new Clock();

        // Create the Core
        orxout(internal_info) << "creating Core object:" << endl;
        this->core_ = new Core(cmdLine);
        this->core_->loadModules();

        // Do this after the Core creation!
        this->config_ = new GameConfig();

        // After the core has been created, we can safely instantiate the GameStates that don't require graphics
        for (const auto& mapEntry : gameStateDeclarations_s)
        {
            if (!mapEntry.second.bGraphicsMode)
                constructedStates_[mapEntry.second.stateName] = GameStateFactory::fabricate(mapEntry.second);
        }

        // The empty root state is ALWAYS loaded!
        this->rootStateNode_ = std::shared_ptr<GameStateTreeNode>(std::make_shared<GameStateTreeNode>());
        this->rootStateNode_->name_ = "emptyRootGameState";
        this->loadedTopStateNode_ = this->rootStateNode_;
        this->loadedStates_.push_back(this->getState(rootStateNode_->name_));

        orxout(internal_status) << "finished initializing Game object" << endl;
    }

    void Game::destroy()
    {
        orxout(internal_status) << "destroying Game object..." << endl;

        assert(loadedStates_.size() <= 1); // Just empty root GameState
        // Destroy all GameStates (std::shared_ptrs take care of actual destruction)
        constructedStates_.clear();

        GameStateFactory::getFactories().clear();
        safeObjectDelete(&config_);
        if (this->core_)
            this->core_->unloadModules();
        safeObjectDelete(&core_);
        safeObjectDelete(&gameClock_);

        orxout(internal_status) << "finished destroying Game object..." << endl;
    }

    /**
    @brief
        Main loop of the orxonox game.
    @note
        We use the Ogre::Timer to measure time since it uses the most precise
        method an any platform (however the windows timer lacks time when under
        heavy kernel load!).
    */
    void Game::run()
    {
        if (this->requestedStateNodes_.empty())
            orxout(user_error) << "Starting game without requesting GameState. This automatically terminates the program." << endl;

        // Update the GameState stack if required. We do this already here to have a properly initialized game before entering the main loop
        this->updateGameStateStack();

        orxout(user_status) << "Game loaded" << endl;
        orxout(internal_status) << "-------------------- starting main loop --------------------" << endl;

        // START GAME
        // first delta time should be about 0 seconds
        this->gameClock_->capture();
        // A first item is required for the fps limiter
        StatisticsTickInfo tickInfo = {0, 0};
        statisticsTickTimes_.push_back(tickInfo);
        while (!this->bAbort_ && (!this->loadedStates_.empty() || this->requestedStateNodes_.size() > 0))
        {
            // Generate the dt
            this->gameClock_->capture();

            // Statistics init
            StatisticsTickInfo tickInfo = {gameClock_->getMicroseconds(), 0};
            statisticsTickTimes_.push_back(tickInfo);
            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();

            // Update the GameState stack if required
            this->updateGameStateStack();

            // Core preUpdate
            try
                { this->core_->preUpdate(*this->gameClock_); }
            catch (...)
            {
                orxout(user_error) << "An exception occurred in the Core preUpdate: " << Exception::handleMessage() << endl;
                orxout(user_error) << "This should really never happen! Closing the program." << endl;
                this->stop();
                break;
            }

            // Update the GameStates bottom up in the stack
            this->updateGameStates();

            // Core postUpdate
            try
                { this->core_->postUpdate(*this->gameClock_); }
            catch (...)
            {
                orxout(user_error) << "An exception occurred in the Core postUpdate: " << Exception::handleMessage() << endl;
                orxout(user_error) << "This should really never happen! Closing the program." << endl;
                this->stop();
                break;
            }

            // Evaluate statistics
            this->updateStatistics();

            // Limit frame rate
            static bool hasVSync = GameMode::showsGraphics() && GraphicsManager::getInstance().hasVSyncEnabled(); // can be static since changes of VSync currently require a restart
            if (this->config_->getFpsLimit() > 0 && !hasVSync)
                this->updateFPSLimiter();
        }

        orxout(internal_status) << "-------------------- finished main loop --------------------" << endl;

        // UNLOAD all remaining states
        while (this->loadedStates_.size() > 1)
            this->unloadState(this->loadedStates_.back()->getName());
        this->loadedTopStateNode_ = this->rootStateNode_;
        this->requestedStateNodes_.clear();
    }

    void Game::updateGameStateStack()
    {
        while (this->requestedStateNodes_.size() > 0)
        {
            std::shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front();
            assert(this->loadedTopStateNode_);
            if (!this->loadedTopStateNode_->parent_.expired() && requestedStateNode == this->loadedTopStateNode_->parent_.lock())
                this->unloadState(loadedTopStateNode_->name_);
            else // has to be child
            {
                try
                {
                    this->loadState(requestedStateNode->name_);
                }
                catch (...)
                {
                    orxout(user_error) << "Loading GameState '" << requestedStateNode->name_ << "' failed: " << Exception::handleMessage() << endl;
                    // All scheduled operations have now been rendered inert --> flush them and issue a warning
                    if (this->requestedStateNodes_.size() > 1)
                        orxout(internal_info) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << endl;
                    this->requestedStateNodes_.clear();
                    break;
                }
            }
            this->loadedTopStateNode_ = requestedStateNode;
            this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
        }
    }

    void Game::updateGameStates()
    {
        // Note: The first element is the empty root state, which doesn't need ticking
        for (const std::shared_ptr<GameState>& state : this->loadedStates_)
        {
            try
            {
                // Add tick time for most of the states
                uint64_t timeBeforeTick = 0;
                if (state->getInfo().bIgnoreTickTime)
                    timeBeforeTick = this->gameClock_->getRealMicroseconds();
                state->update(*this->gameClock_);
                if (state->getInfo().bIgnoreTickTime)
                    this->subtractTickTime(static_cast<int32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
            }
            catch (...)
            {
                orxout(user_error) << "An exception occurred while updating '" << state->getName() << "': " << Exception::handleMessage() << endl;
                orxout(user_error) << "This should really never happen!" << endl;
                orxout(user_error) << "Unloading all GameStates depending on the one that crashed." << endl;
                std::shared_ptr<GameStateTreeNode> current = this->loadedTopStateNode_;
                while (current->name_ != state->getName() && current)
                    current = current->parent_.lock();
                if (current && current->parent_.lock())
                    this->requestState(current->parent_.lock()->name_);
                else
                    this->stop();
                break;
            }
        }
    }

    void Game::updateStatistics()
    {
        // Add the tick time of this frame (rendering time has already been subtracted)
        uint64_t currentTime = gameClock_->getMicroseconds();
        uint64_t currentRealTime = gameClock_->getRealMicroseconds();
        this->statisticsTickTimes_.back().tickLength += (uint32_t)(currentRealTime - currentTime);
        this->periodTickTime_ += (uint32_t)(currentRealTime - currentTime);
        if (this->periodTime_ > this->config_->getStatisticsRefreshCycle())
        {
            std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
            assert(it != this->statisticsTickTimes_.end());
            int64_t lastTime = currentTime - this->config_->getStatisticsAvgLength();
            if (static_cast<int64_t>(it->tickTime) < lastTime)
            {
                do
                {
                    assert(this->periodTickTime_ >= it->tickLength);
                    this->periodTickTime_ -= it->tickLength;
                    ++it;
                    assert(it != this->statisticsTickTimes_.end());
                } while (static_cast<int64_t>(it->tickTime) < lastTime);
                this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
            }

            uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
            // Why minus 1? No idea, but otherwise the fps rate is always (from 10 to 200!) one frame too low
            this->avgFPS_ = -1 + static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f;
            this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f;

            this->periodTime_ -= this->config_->getStatisticsRefreshCycle();
        }
    }

    void Game::updateFPSLimiter()
    {
        uint64_t nextTime = gameClock_->getMicroseconds() - excessSleepTime_ + static_cast<uint32_t>(1000000.0f / this->config_->getFpsLimit());
        uint64_t currentRealTime = gameClock_->getRealMicroseconds();
        while (currentRealTime < nextTime - minimumSleepTime_)
        {
            usleep((unsigned long)(nextTime - currentRealTime));
            currentRealTime = gameClock_->getRealMicroseconds();
        }
        // Integrate excess to avoid steady state error
        excessSleepTime_ = (int)(currentRealTime - nextTime);
        // Anti windup
        if (excessSleepTime_ > 50000) // 20ms is about the maximum time Windows would sleep for too long
            excessSleepTime_ = 50000;
    }

    void Game::stop()
    {
        orxout(user_status) << "Exit" << endl;
        this->bAbort_ = true;
    }

    void Game::subtractTickTime(int32_t length)
    {
        assert(!this->statisticsTickTimes_.empty());
        this->statisticsTickTimes_.back().tickLength -= length;
        this->periodTickTime_ -= length;
    }


    /***** GameState related *****/

    void Game::requestState(const std::string& name)
    {
        if (!this->checkState(name))
        {
            orxout(user_warning) << "GameState named '" << name << "' doesn't exist!" << endl;
            return;
        }

        if (this->bChangingState_)
        {
            orxout(user_warning) << "Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << endl;
            return;
        }

        std::shared_ptr<GameStateTreeNode> lastRequestedNode;
        if (this->requestedStateNodes_.empty())
            lastRequestedNode = this->loadedTopStateNode_;
        else
            lastRequestedNode = this->requestedStateNodes_.back();
        if (name == lastRequestedNode->name_)
        {
            orxout(user_warning) << "Requesting the currently active state! Ignoring." << endl;
            return;
        }

        // Check children first
        std::vector<std::shared_ptr<GameStateTreeNode>> requestedNodes;
        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
        {
            if (lastRequestedNode->children_[i]->name_ == name)
            {
                requestedNodes.push_back(lastRequestedNode->children_[i]);
                break;
            }
        }

        if (requestedNodes.empty())
        {
            // Check parent and all its grand parents
            std::shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode;
            while (currentNode != nullptr)
            {
                if (currentNode->name_ == name)
                    break;
                currentNode = currentNode->parent_.lock();
                requestedNodes.push_back(currentNode);
            }
            if (currentNode == nullptr)
                requestedNodes.clear();
        }

        if (requestedNodes.empty())
            orxout(user_error) << "Requested GameState transition is not allowed. Ignoring." << endl;
        else
            this->requestedStateNodes_.insert(requestedStateNodes_.end(), requestedNodes.begin(), requestedNodes.end());
    }

    void Game::requestStates(const std::string& names)
    {
        SubString tokens(names, ",;", " ");
        for (unsigned int i = 0; i < tokens.size(); ++i)
            this->requestState(tokens[i]);
    }

    void Game::popState()
    {
        std::shared_ptr<GameStateTreeNode> lastRequestedNode;
        if (this->requestedStateNodes_.empty())
            lastRequestedNode = this->loadedTopStateNode_;
        else
            lastRequestedNode = this->requestedStateNodes_.back();
        if (lastRequestedNode != this->rootStateNode_)
            this->requestState(lastRequestedNode->parent_.lock()->name_);
        else
            orxout(internal_warning) << "Can't pop the internal dummy root GameState" << endl;
    }

    std::shared_ptr<GameState> Game::getState(const std::string& name)
    {
        GameStateMap::const_iterator it = constructedStates_.find(name);
        if (it != constructedStates_.end())
            return it->second;
        else
        {
            std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
            if (it != gameStateDeclarations_s.end())
                orxout(internal_error) << "GameState '" << name << "' has not yet been loaded." << endl;
            else
                orxout(internal_error) << "Could not find GameState '" << name << "'." << endl;
            return std::shared_ptr<GameState>();
        }
    }

    void Game::setStateHierarchy(const std::string& str)
    {
        // Split string into pieces of the form whitespacesText
        std::vector<std::pair<std::string, int>> stateStrings;
        size_t pos = 0;
        size_t startPos = 0;
        while (pos < str.size())
        {
            int indentation = 0;
            while (pos < str.size() && str[pos] == ' ')
                ++indentation, ++pos;
            startPos = pos;
            while (pos < str.size() && str[pos] != ' ')
                ++pos;
            stateStrings.emplace_back(str.substr(startPos, pos - startPos), indentation);
        }
        if (stateStrings.empty())
            ThrowException(GameState, "Emtpy GameState hierarchy provided, terminating.");
        // Add element with large identation to detect the last with just an iterator
        stateStrings.emplace_back(std::string(), -1);

        // Parse elements recursively
        std::vector<std::pair<std::string, int>>::const_iterator begin = stateStrings.begin();
        parseStates(begin, this->rootStateNode_);
    }

    /*** Internal ***/

    void Game::parseStates(std::vector<std::pair<std::string, int>>::const_iterator& it, std::shared_ptr<GameStateTreeNode> currentNode)
    {
        SubString tokens(it->first, ",");
        std::vector<std::pair<std::string, int>>::const_iterator startIt = it;

        for (unsigned int i = 0; i < tokens.size(); ++i)
        {
            it = startIt; // Reset iterator to the beginning of the sub tree
            if (!this->checkState(tokens[i]))
                ThrowException(GameState, "GameState with name '" << tokens[i] << "' not found!");
            if (tokens[i] == this->rootStateNode_->name_)
                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
            std::shared_ptr<GameStateTreeNode> node(std::make_shared<GameStateTreeNode>());
            node->name_ = tokens[i];
            node->parent_ = currentNode;
            currentNode->children_.push_back(node);

            int currentLevel = it->second;
            ++it;
            while (it->second != -1)
            {
                if (it->second <= currentLevel)
                    break;
                else if (it->second == currentLevel + 1)
                    parseStates(it, node);
                else
                    ThrowException(GameState, "Indentation error while parsing the hierarchy.");
            }
        }
    }

    void Game::loadGraphics()
    {
        if (!GameMode::showsGraphics())
        {
            orxout(user_status) << "Loading graphics" << endl;
            orxout(internal_info) << "loading graphics in Game" << endl;

            core_->loadGraphics();
            Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics, true);

            // Construct all the GameStates that require graphics
            for (const auto& mapEntry : gameStateDeclarations_s)
            {
                if (mapEntry.second.bGraphicsMode)
                {
                    // Game state loading failure is serious --> don't catch
                    std::shared_ptr<GameState> gameState = GameStateFactory::fabricate(mapEntry.second);
                    if (!constructedStates_.insert(std::make_pair(
                        mapEntry.second.stateName, gameState)).second)
                        assert(false); // GameState was already created!
                }
            }
            graphicsUnloader.Dismiss();

            orxout(internal_info) << "finished loading graphics in Game" << endl;
        }
    }

    void Game::unloadGraphics(bool loadGraphicsManagerWithoutRenderer)
    {
        if (GameMode::showsGraphics())
        {
            orxout(user_status) << "Unloading graphics" << endl;
            orxout(internal_info) << "unloading graphics in Game" << endl;

            // Destroy all the GameStates that require graphics
            for (GameStateMap::iterator it = constructedStates_.begin(); it != constructedStates_.end();)
            {
                if (it->second->getInfo().bGraphicsMode)
                    constructedStates_.erase(it++);
                else
                    ++it;
            }

            core_->unloadGraphics(loadGraphicsManagerWithoutRenderer);
        }
    }

    bool Game::checkState(const std::string& name) const
    {
        std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
        if (it == gameStateDeclarations_s.end())
            return false;
        else
            return true;
    }

    void Game::loadState(const std::string& name)
    {
        orxout(internal_status) << "loading state '" << name << "'" << endl;

        this->bChangingState_ = true;
        LOKI_ON_BLOCK_EXIT_OBJ(*this, &Game::resetChangingState); (void)LOKI_ANONYMOUS_VARIABLE(scopeGuard);

        // If state requires graphics, load it
        Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics, true);
        if (gameStateDeclarations_s[name].bGraphicsMode && !GameMode::showsGraphics())
            this->loadGraphics();
        else
            graphicsUnloader.Dismiss();

        std::shared_ptr<GameState> state = this->getState(name);
        state->activateInternal();
        if (!this->loadedStates_.empty())
            this->loadedStates_.back()->activity_.topState = false;
        this->loadedStates_.push_back(state);
        state->activity_.topState = true;

        graphicsUnloader.Dismiss();
    }

    void Game::unloadState(const std::string& name)
    {
        orxout(internal_status) << "unloading state '" << name << "'" << endl;

        this->bChangingState_ = true;
        try
        {
            std::shared_ptr<GameState> state = this->getState(name);
            state->activity_.topState = false;
            this->loadedStates_.pop_back();
            if (!this->loadedStates_.empty())
                this->loadedStates_.back()->activity_.topState = true;
            state->deactivateInternal();
        }
        catch (...)
        {
            orxout(internal_warning) << "Unloading GameState '" << name << "' threw an exception: " << Exception::handleMessage() << endl;
            orxout(internal_warning) << "There might be potential resource leaks involved! To avoid this, improve exception-safety." << endl;
        }
        // Check if graphics is still required
        bool graphicsRequired = false;
        for (const std::shared_ptr<GameState>& state : loadedStates_)
            graphicsRequired |= state->getInfo().bGraphicsMode;
        if (!graphicsRequired)
            this->unloadGraphics(!this->bAbort_); // if abort is false, that means the game is still running while unloading graphics. in this case we load a graphics manager without renderer (to keep all necessary ogre instances alive)
        this->bChangingState_ = false;
    }

    /*static*/ std::map<std::string, std::shared_ptr<Game::GameStateFactory>>& Game::GameStateFactory::getFactories()
    {
        static std::map<std::string, std::shared_ptr<GameStateFactory>> factories;
        return factories;
    }

    /*static*/ std::shared_ptr<GameState> Game::GameStateFactory::fabricate(const GameStateInfo& info)
    {
        std::map<std::string, std::shared_ptr<Game::GameStateFactory>>::const_iterator it = getFactories().find(info.className);
        assert(it != getFactories().end());
        return it->second->fabricateInternal(info);
    }
}
