#include "GameMapCamera.h"
#include "EngineCore/Game.h"
#include "Actor/Map/GameMap.h"
#include "Actor/Object/BaseObject.h"
#include <algorithm>

GameMapCamera::GameMapCamera()
{
}

GameMapCamera::~GameMapCamera()
{
}

void GameMapCamera::SetParentMap(GameMap *map)
{
    this->_ParentMap = map;
    _ParentMap->_Camera = this;
}

void GameMapCamera::SetFromActor(BaseObject *actor)
{
    this->_FromActor = actor;
}

void GameMapCamera::Update(float deltaTime)
{
    SyncPosByFromParent(deltaTime);
}

void GameMapCamera::SetPos(int x, int y, int z)
{
    this->X = x;
    this->Y = y;
    this->Z = z;
}

void GameMapCamera::AddPos(int x, int y, int z)
{
    this->X += x;
    this->Y += y;
    this->Z += z;
}

void GameMapCamera::SyncPosByFromParent(float deltaTime)
{
    if (this->_FromActor != nullptr)
    {
        float width_Separate = Game::GetInstance().Screen_W / 2;
        float height_Separate = Game::GetInstance().Screen_H / 2;
        int R_X, R_Y, R_Z;
        R_X = std::fmin(std::fmax(this->_FromActor->Position.x, width_Separate), _ParentMap->_MapLength - width_Separate);
        R_Y = std::fmin(std::fmax(this->_FromActor->Position.y, height_Separate), _ParentMap->_MapHeight - height_Separate);
        R_Z = 0;
        // SDL_Log("R_X: %d, R_Y: %d, R_Z: %d", R_X, R_Y, R_Z);
        // SetPos(R_X, R_Y, R_Z);

        for (auto Layer : _ParentMap->_LayerMap)
        {
            if (Layer.first == "distantback")
            {
                Layer.second->SetPos(VecFPos((-R_X + width_Separate) * BackgroundMoveSpeed, -R_Y + R_Z + height_Separate + 120 + BackgroundOffset));
            }
            else
                Layer.second->SetPos(VecFPos((-R_X + width_Separate), -R_Y + R_Z + height_Separate + 120 + BackgroundOffset));
        }
    }
}
