#include "pch.h"
#include "imgui.h"
#include "Player.h"

#include <algorithm>

#include "colors.h"
#include "utils.h"
#include "Levels/World/WorldLevel.h"
#include "Animations/Animation.h"
#include "GridSystem/WorldTile.h"

Player::Player(const Vector2f& Position, TextureManager* manager) : m_Position(Position), m_Size(Vector2f { 40, 40 }), m_Vel(Vector2f { 0, 0 }), m_Acc(Vector2f { 0, 0 }) {
	m_ContactMap[Collision::CollisionDirection::Top] = nullptr;
	m_ContactMap[Collision::CollisionDirection::Bottom] = nullptr;
	m_ContactMap[Collision::CollisionDirection::Left] = nullptr;
	m_ContactMap[Collision::CollisionDirection::Right] = nullptr;

	m_walkAnimation = new Animation(
		manager->GetTexture("animations/player/player_walk.png"),
		8, 0.1f, Rectf { 0, 0, 70, 70 });
	m_currentAnimation = m_walkAnimation;
}

Collision::CollisionRect Player::GetCollisionRect() const {
	Collision::CollisionRect rect = { m_Position, m_Size, m_Vel };
	return rect;
}

void Player::Draw() const {
	if (m_DrawCollisionRect) {
		utils::SetColor(Colors::PINK);
		utils::DrawRect(Rectf { m_Position.x, m_Position.y, m_Size.x, m_Size.y });
	}
	Vector2f center = m_Position + m_Size / 2;

	const int frameWidth = 70; //TODO: fix this
	int halfFrameWidth = frameWidth / 2;
	float bobOffset = m_BobUp ? 1 : 0;
	Vector2f drawPos = Vector2f { center.x - halfFrameWidth, center.y - halfFrameWidth + 9 + bobOffset };

	m_walkAnimation->Draw(drawPos, Rectf { drawPos.x, drawPos.y, frameWidth, frameWidth });
	utils::DrawEllipse(m_DigDestination, 5, 5);
	utils::DrawEllipse(m_DigStart, 5, 5);
}
void Player::ProcessImGui() {
	ImGui::Begin("Collision Info", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
	ImGui::Text("is Grounded: %s", m_Grounded ? "true" : "false");
	ImGui::Checkbox("Draw Collision Rect", &m_DrawCollisionRect);
	std::string currentState {};
	switch (m_State) {
	case PlayerState::Idle:
		currentState = "Idle";
		break;
	case PlayerState::Digging:
		currentState = "Digging";
		break;
	case PlayerState::Walking:
		currentState = "Walking";
		break;
	}
	ImGui::Text("Player State %s", currentState.c_str());
	ImGui::Text("Bob counter: %f", m_BobTimer);
	ImGui::Text("Bob up: %s", m_BobUp ? "true" : "false");


	//ContactMap
	ImGui::Text("ContactMap:");
	ImGui::Text("Top: %s", m_ContactMap[Collision::CollisionDirection::Top] != nullptr ? "true" : "false");
	ImGui::Text("Bottom: %s", m_ContactMap[Collision::CollisionDirection::Bottom] != nullptr ? "true" : "false");
	ImGui::Text("Left: %s", m_ContactMap[Collision::CollisionDirection::Left] != nullptr ? "true" : "false");
	ImGui::Text("Right: %s", m_ContactMap[Collision::CollisionDirection::Right] != nullptr ? "true" : "false");
	ImGui::End();
}
void Player::Dig(Collision::CollisionDirection dir, WorldLevel& level) {
	m_State = PlayerState::Digging;
	m_DigProgress = 0;
	m_DigTile = m_ContactMap[dir];
	//Set the digging location in the center of the destination tile;
	const WorldTile* tile = m_ContactMap[dir];
	//Add case for bottom because otherwise i clip through the floor
	m_DigDestination = tile->GetPosition();
	if (dir == Collision::Bottom) {
		m_DigDestination += Vector2f { 0, 2 };
		//Center
		m_DigDestination.x += tile->GetSize().x / 2 - m_Size.x / 2;
	}
	if(dir == Collision::Left) {
		m_DigDestination += Vector2f{ 2, 0};
	}
	m_ContactMap[dir] = nullptr;
}

bool Player::CanDig(Collision::CollisionDirection dir, WorldLevel& level) {
	WorldTile* tile = m_ContactMap[dir];
	if (tile == nullptr) {
		return false;
	}
	GroundTileType type = *tile->GetTileType();
	//TODO: Add a list of non diggable tiles

	if (type == Tiles::Special::HARD_LEFT || type == Tiles::Special::HARD_MIDDLE || type == Tiles::Special::HARD_RIGHT) {
		return false;
	}

	return true;
}

void Player::Update(float elapsedTime, WorldLevel& level) {
	m_BobTimer += elapsedTime;
	if (m_BobTimer >= m_BobTime) {
		m_BobUp = !m_BobUp;
		m_BobTimer = 0.0f;
	}

	//check for keys
	if (m_State != PlayerState::Digging) {
		m_Vel = Vector2f { 0, -100 };
		if (utils::isKeyDown(SDL_SCANCODE_W)) {
			m_Vel.y = 100;
			m_Grounded = false;
		}
		if (utils::isKeyPressed(SDL_SCANCODE_S)) {
			if (m_Grounded) {
				if (this->CanDig(Collision::Bottom, level)) {
					this->Dig(Collision::CollisionDirection::Bottom, level);
				}
			}
			else {
				m_Vel.y = -100;
			}
		}
		if (utils::isKeyDown(SDL_SCANCODE_A)) {
			m_walkAnimation->SetFlipped(false);
			m_Vel.x = -100;
			if (m_Grounded && !m_DidJustDigLeft) {
				//Check if the player doesnt come from digging a tile
				if (this->CanDig(Collision::CollisionDirection::Left, level)) {
					this->Dig(Collision::CollisionDirection::Left, level);
					m_DidJustDigLeft = true;
				}
			}
		}
		if (m_DidJustDigLeft) {
			if (!utils::isKeyDown(SDL_SCANCODE_A)) {
				m_DidJustDigLeft = false;
			}
		}

		if (utils::isKeyDown(SDL_SCANCODE_D)) {
			m_Vel.x = 100;
			m_walkAnimation->SetFlipped(true);
			if (m_Grounded && !m_DidJustDigRight) {
				//Check if the player doesnt come from digging a tile
				if (this->CanDig(Collision::CollisionDirection::Right, level)) {
					this->Dig(Collision::CollisionDirection::Right, level);
					m_DidJustDigRight = true;
				}
			}
		}
		if (m_DidJustDigRight) {
			if (!utils::isKeyDown(SDL_SCANCODE_D)) {
				m_DidJustDigRight = false;
			}
		}

	
		m_walkAnimation->Update(elapsedTime);


		m_ContactMap[Collision::CollisionDirection::Top] = nullptr;
		m_ContactMap[Collision::CollisionDirection::Bottom] = nullptr;
		m_ContactMap[Collision::CollisionDirection::Left] = nullptr;
		m_ContactMap[Collision::CollisionDirection::Right] = nullptr;
		m_Grounded = false;


		float t = 0, min_t = INFINITY;
		Vector2f intersectionPoint, normal;

		std::vector<std::pair<int, float>> contactTimes {};

		const WorldGridManager& gridManager = level.GetGridManager();

		for (int x { 0 }; x < WORLD_WIDTH; ++x) {
			for (int y { 0 }; y < WORLD_HEIGHT; ++y) {
				WorldTile* tile = gridManager.GetTileAtIndex(x, y);
				if (*tile->GetTileType() != Tiles::AIR) {
					tile->m_Hightlight = false;
					if (Collision::DynamicRectVsRect(this->GetCollisionRect(), elapsedTime, tile->GetCollisionRect().getCollisionRect(), intersectionPoint, normal, t)) {
						contactTimes.emplace_back(std::pair<int, float> { x + y * WORLD_WIDTH, t });
					}
				}
			}
		}

		std::sort(contactTimes.begin(), contactTimes.end(), [](const std::pair<int, float>& a, const std::pair<int, float>& b) {
			return a.second < b.second;
		});

		for (std::pair<int, float> contact_time : contactTimes) {
			int x = contact_time.first % WORLD_WIDTH;
			int y = contact_time.first / WORLD_WIDTH;
			WorldTile* world_tile = gridManager.GetTileAtIndex(x, y);

			const Vector2f WorldTilePos = world_tile->GetCollisionRect().getCollisionRect().pos;
			const Vector2f WorldTileSize = world_tile->GetCollisionRect().getCollisionRect().size;

			if (WorldTilePos.y + WorldTileSize.y > m_Position.y) {
				if (WorldTilePos.x + WorldTileSize.x > m_Position.x) {
					if (WorldTilePos.y + WorldTileSize.y / 2 > m_Position.y && m_Position.y + m_Size.y / 2 > WorldTilePos.y) {
						//Right of player
						m_ContactMap[Collision::CollisionDirection::Right] = world_tile;
					}
				}
			}

			if (WorldTilePos.y + WorldTileSize.y > m_Position.y) {
				if (WorldTilePos.x < m_Position.x + m_Size.x) {
					if (WorldTilePos.y + WorldTileSize.y / 2 > m_Position.y && m_Position.y + m_Size.y / 2 > WorldTilePos.y) {
						//Left of player
						m_ContactMap[Collision::CollisionDirection::Left] = world_tile;
					}
				}
			}

			//Below the player
			if (WorldTilePos.y + WorldTileSize.y <= m_Position.y) {
				if (WorldTilePos.x + WorldTileSize.x / 2 > m_Position.x && m_Position.x + m_Size.x / 2 > WorldTilePos.x) {
					m_ContactMap[Collision::CollisionDirection::Bottom] = world_tile;
					m_Grounded = true;
					world_tile->m_Hightlight = true;
				}
			}

			Collision::CollisionRect rect = world_tile->GetCollisionRect().getCollisionRect(); //TODO: fix this mess
			Collision::ResolvePlayerVsRect(*this, elapsedTime, &rect);
		}
		if (m_State != PlayerState::Digging) { //Fix for when the state is JUST set to digging
			if (m_Vel.x != 0.0f) {
				m_State = PlayerState::Walking;
			}
			else {
				m_State = PlayerState::Idle;
			}
		}
	}
	switch (m_State) {
	case PlayerState::Idle:
		m_walkAnimation->SetPlaying(false);
		break;
	case PlayerState::Walking:
		m_walkAnimation->SetPlaying(true);
		break;
	case PlayerState::Digging: {
		m_walkAnimation->SetPlaying(false);
		//Diganimation

		if (!m_Digging) { //TODO: fix for setting the start position
			m_Digging = true;
			m_DigStart = m_Position;
		}

		m_DigProgress += elapsedTime;
		//lerp to the destination
		float progress = utils::map(m_DigProgress, 0.0f, m_DigTime, 0.0f, 1.0f);
		std::cout << progress << '\n';
		m_Position = utils::lerp(m_DigStart, m_DigDestination, progress);
		if (progress >= 0.5f && !m_HasDeletedTile) {
			m_DigTile->SetTileType(Tiles::AIR);
			m_DigTile = nullptr;
			m_HasDeletedTile = true;
		}
		if (progress >= 1.0f) {
			m_State = PlayerState::Idle;
			m_HasDeletedTile = false;
			m_Digging = false;
		}
		break;
	}
	default:
		break;
	}

	if (m_State != PlayerState::Digging) {
		m_Position = m_Position + m_Vel * elapsedTime;
	}
}
