/*Copyright (C) 2010-2023 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu 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.

Hikou no mizu 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 Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "CallbackAnimation.hpp"

namespace
{
    bool LAG_MITIGATION = false;
}

namespace AnimationLag
{
    void enableLagMitigation()
    {
        LAG_MITIGATION = true;
    }

    void disableLagMitigation()
    {
        LAG_MITIGATION = false;
    }
}

CallbackAnimation::CallbackAnimation() :
Animation(), m_receiver(nullptr), m_furthestFrame(0)
{

}

void CallbackAnimation::setReceiver(AnimationCallbackReceiver *receiver)
{
    m_receiver = receiver;
}

void CallbackAnimation::addStepImpactCallback(std::size_t frameIx)
{
    if (frameIx < m_framesList.size())
        m_stepImpactCallbacks.push_back(frameIx);
}

void CallbackAnimation::reset()
{
    Animation::reset();
    m_furthestFrame = 0;
}

void CallbackAnimation::goToTime(float time)
{
    Animation::goToTime(time);
    const std::size_t frameEnd = getCurrentFrame();

    //Compute the number of frame steps from m_furthestFrame to frameEnd
    //Looping through the animation if frameEnd < m_furthestFrame
    const std::size_t frameStep = (frameEnd >= m_furthestFrame)
        ? frameEnd - m_furthestFrame
        : getFrameSize() - m_furthestFrame + frameEnd;

    //Accept the frame step update for callbacks only if it does not deviate
    //too strongly from the expected frame increment
    //(frame steps of over a quarter the size of the animation
    // are likely caused by a delayed server packet)
    if (!LAG_MITIGATION || frameStep < getFrameSize() / 4)
    {
        if (m_receiver != nullptr)
        {
            for (std::size_t impact : m_stepImpactCallbacks)
            {
                if (m_furthestFrame <= impact && impact < frameEnd)
                    m_receiver->stepImpactCallback();
            }
        }

        m_furthestFrame = frameEnd;
    }
}

void CallbackAnimation::forceTime(float time)
{
    Animation::goToTime(time);
}
