/*
 *   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:
 *      Cyrill Burgener
 *
 */

/**
    @file TimeHUD.cc
    @brief Implementation of the TimeHUD
*/


#include "TimeHUD.h"

#include "core/CoreIncludes.h"
#include "util/Convert.h"
#include "Hover.h"

namespace orxonox
{
    RegisterClass(TimeHUD);

    TimeHUD::TimeHUD(Context* context) : OverlayText(context)
    {
        RegisterObject(TimeHUD);

        this->time_ = 0.0f;
        this->running_ = false;
        this->hoverGame_ = nullptr;
        setRunning(true);
    }

    inline std::string getTimeString(float time) {
        std::ostringstream ss;

        int h = ((int) (time * 100.0f)) % 100;
        int s = ((int) time) % 60;
        int m = (int) (time / 60.0f);

        ss << m << ":";

        if(s < 10) {
            ss << 0;
        }
        ss << s << ":";

        if(h < 10) {
            ss << 0;
        }
        ss << h << "s";
        return ss.str();
    }

    void TimeHUD::tick(float dt)
    {
        SUPER(TimeHUD, tick, dt);

        if(this->running_) {
            this->time_ += dt;
        }
        if (this->hoverGame_)
        {
            this->setCaption(getTimeString(this->time_));
            if (this->hoverGame_->getNumberOfFlags() == 0)
                setRunning(false);
        }
        
    }

    void TimeHUD::changedOwner()
    {
        SUPER(TimeHUD, changedOwner);

        if (this->getOwner() && this->getOwner()->getGametype())
        {
            this->hoverGame_ = orxonox_cast<Hover*>(this->getOwner()->getGametype());
        }
        else
        {
            this->hoverGame_ = nullptr;
        }
    }

    void TimeHUD::reset()
    {
        this->time_ = 0;
    }
}
