/*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 "NetServerController.hpp"
#include "Player/Player.hpp"
#include "Network/Serialization/PlayerAction.hpp"

NetServerController::NetServerController() : PlayerController(),
m_crouching(false), m_movingLeft(false), m_movingRight(false)
{

}

void NetServerController::act()
{
    if (m_player != nullptr && m_player->getAttack() == AttackIndex::Default &&
        !m_player->isKo() && !m_player->isHit())
    {
        if (m_movingLeft)
            m_player->setMoving(MovingState::MovingLeft);
        else if (m_movingRight)
            m_player->setMoving(MovingState::MovingRight);
        else
        {
            m_player->setMoving(MovingState::NotMoving);
            if (m_crouching)
            {
                if (m_player->getState() != StateIndex::Crouched)
                    m_player->crouch();
            }
            else if (m_player->getState() == StateIndex::Crouched)
                m_player->uncrouch();
        }
    }
}

void NetServerController::playerActionReceived(const PlayerAction &action)
{
    if (m_player != nullptr)
    {
        PlayerAction::Index actionIx = action.getIndex();
        if (actionIx == PlayerAction::Index::MoveLeft)
        {
            m_movingLeft = true;
            m_movingRight = false;
        }
        else if (actionIx == PlayerAction::Index::MoveRight)
        {
            m_movingLeft = false;
            m_movingRight = true;
        }
        else if (actionIx == PlayerAction::Index::StopMoving)
        {
            m_movingLeft = false;
            m_movingRight = false;
        }
        else if (actionIx == PlayerAction::Index::Crouch)
            m_crouching = true;
        else if (actionIx == PlayerAction::Index::Uncrouch)
            m_crouching = false;

        action.applyPunctual((*m_player));
    }
}

const PlayerStatus &NetServerController::getPlayerStatus()
{
    if (m_player != nullptr)
        m_playerStatus.readFromPlayer((*m_player));

    return m_playerStatus;
}

void NetServerController::reset()
{
    m_movingLeft = false;
    m_movingRight = false;
    m_crouching = false;
}
