// IAEngine: 2D Game Engine by IA
// Copyright (C) 2025 IASoft (PVT) LTD (oss@iasoft.dev)
//
// 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 3 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, see <https://www.gnu.org/licenses/>.

#include <IAEngine/Engine.hpp>
#include <Time.hpp>

namespace ia::iae
{
    FLOAT32 g_globalTimeScale = 1.0f;

    FLOAT32 g_deltaTime{1 / 60.0f};
    INT64 g_lastFrameTick{0};

    std::chrono::time_point<std::chrono::high_resolution_clock> g_startMS;

    VOID Time::Initialize()
    {
        g_startMS = std::chrono::high_resolution_clock::now();
    }

    VOID Time::Terminate()
    {
    }

    VOID Time::NextFrame()
    {
        const auto t = GetTickCount();
        g_deltaTime = t - g_lastFrameTick;
        g_lastFrameTick = t;
    }

    INT64 Time::GetTickCount()
    {
        return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() -
                                                                     g_startMS)
            .count();
    }

    INT64 Time::GetCurrentSecond()
    {
        return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - g_startMS)
            .count();
    }

    FLOAT32 Time::GetFrameDeltaTime()
    {
        return g_deltaTime * g_globalTimeScale;
    }

    INT64 Time::GetUnixSecond()
    {
        return std::chrono::duration_cast<std::chrono::seconds>(
                   std::chrono::system_clock::now().time_since_epoch()).count();
    }

    INT64 Time::GetUnixMillisecond()
    {
        return std::chrono::duration_cast<std::chrono::milliseconds>(
                   std::chrono::system_clock::now().time_since_epoch()).count();
    }
} // namespace ia::iae

namespace ia::iae
{
    VOID Engine::SetTimeScale(IN FLOAT32 scale)
    {
        g_globalTimeScale = scale;
    }

    INT64 Engine::GetTickCount()
    {
        return Time::GetTickCount();
    }

    INT64 Engine::GetUnixSecond()
    {
        return Time::GetUnixSecond();
    }

    INT64 Engine::GetUnixMillisecond()
    {
        return Time::GetUnixMillisecond();
    }

    FLOAT32 Engine::GetFrameDeltaTime()
    {
        return Time::GetFrameDeltaTime();
    }
} // namespace ia::iae