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

#include <algorithm>

#include "colors.h"
#include "GameManager.h"
#include "GridSystem/GroundTileTypeManager.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 }, true);
	m_TurnAnimation = new Animation(
		manager->GetTexture("animations/player/player_turn.png"),
		5, 0.07f, Rectf { 0, 0, 70, 70 }, false);
	m_DigStartAnimation = new Animation(
		manager->GetTexture("animations/player/player_dig_start.png"),
		7, 0.07f, Rectf { 0, 0, 70, 70 }, false);
	m_DigAnimation = new Animation(
		manager->GetTexture("animations/player/player_dig.png"),
		7, 0.05f, Rectf { 0, 0, 70, 70 }, true);

	m_FlyStartAnimation = new Animation(
		manager->GetTexture("animations/player/player_fly_start.png"),
		12, 0.05f, Rectf { 0, 0, 70, 70 }, false);

	m_FlyAnimation = new Animation(
		manager->GetTexture("animations/player/player_fly.png"),
		5, 0.01f, Rectf { 0, 0, 70, 70 }, true);

	m_FlyTurnAnimation = new Animation(
		manager->GetTexture("animations/player/player_fly_turn.png"),
		3, 0.05f, Rectf { 0, 0, 70, 70 }, false);

	m_DieStartAnimation = new Animation(
		manager->GetTexture("animations/player/player_die_start.png"),
		11, 0.05f, Rectf { 0, 0, 100, 100 }, false);

	m_DieLoopAnimation = new Animation(
		manager->GetTexture("animations/player/player_die_loop.png"),
		4, 0.05f, Rectf { 0, 0, 100, 100 }, true);

	m_CurrentAnimation = m_WalkAnimation;


	m_IdleSound = new SoundEffect("sound/idle.wav");
	m_FlySound = new SoundEffect("sound/fly.wav");
	m_DigSound = new SoundEffect("sound/drill.wav");
	m_DigSound->SetVolume(64);
	m_WalkSound = new SoundEffect("sound/walk.wav");
	m_CurrentSound = m_IdleSound;

}

Player::~Player() {
	delete m_WalkAnimation;
	delete m_TurnAnimation;
	delete m_DigAnimation;
	delete m_DigStartAnimation;

	delete m_IdleSound;
	delete m_FlySound;
	delete m_DigSound;
	delete m_WalkSound;

	delete m_FlyStartAnimation;
	delete m_FlyAnimation;
	delete m_FlyTurnAnimation;

	delete m_DieStartAnimation;
	delete m_DieLoopAnimation;

	for (Particle* particle : m_DigParticles) {
		delete particle;
	}

	for (Particle* particle : m_SmokeParticles) {
		delete particle;
	}
}

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;
	int bobOffset = m_BobUp ? 1 : 0;

	float rotateOffset = std::abs(m_Vel.x) / 30;
	Vector2f drawPos = Vector2f { center.x, center.y + 9 + bobOffset };
	glPushMatrix();
	glTranslatef(drawPos.x - halfFrameWidth, drawPos.y - halfFrameWidth, 0);
	if (!m_Grounded && std::abs(m_Vel.y) > 0.1f) {
		glRotatef(m_Direction == PlayerDirection::Left ? rotateOffset : -rotateOffset, 0, 0, 1);
	}
	{
		utils::SetColor(Colors::WHITE);
		m_CurrentAnimation->Draw(Vector2f { 0, 0 }, Rectf { 0, 0, frameWidth, frameWidth });

		
	}
	glPopMatrix();
	for (Particle* particle : m_DigParticles) {
		utils::SetColor(Colors::WHITE);
		particle->Draw();
	}

	for (Particle* particle : m_SmokeParticles) {
		utils::SetColor(Colors::WHITE);
		particle->Draw();
	}

	
}
void Player::Die() {
	m_IsDead = true;
	m_CurrentAnimation = m_DieStartAnimation;
	m_HasPlayedDeathAnimation = false;
}
void Player::Dig(Collision::CollisionDirection dir, WorldLevel&) {
	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];
	m_ToAddPoints = tile->GetTileType()->GetValue();
	m_ToAddTile = tile->GetTileType();
	//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&) {
	WorldTile* tile = m_ContactMap[dir];
	if (tile == nullptr) {
		return false;
	}
	GroundTileType type = *tile->GetTileType();

	if (type == GroundTileTypeManager::GetInstance()->STONE) {
		return false;
	}

	if (type == GroundTileTypeManager::GetInstance()->HARD_LEFT || type == GroundTileTypeManager::GetInstance()->HARD_MIDDLE || type == GroundTileTypeManager::GetInstance()->
		HARD_RIGHT) {
		return false;
	}

	return true;
}
void Player::ChangeSound(SoundEffect* sound) {
	m_PrevSound = m_CurrentSound;
	// m_CurrentSound->Stop();
	m_CurrentSound = sound;
}

void Player::Update(float elapsedTime, WorldLevel& level) {


	if (m_IsDead) {
		m_CurrentAnimation->Update(elapsedTime);
		if (m_CurrentAnimation == m_DieStartAnimation) {
			if (m_CurrentAnimation->IsDone()) {
				m_CurrentAnimation = m_DieLoopAnimation;
			}
		}
		return;
	}

	m_BobTimer += elapsedTime;
	if (m_BobTimer >= m_BobTime) {
		m_BobUp = !m_BobUp;
		m_BobTimer = 0.0f;
	}


	std::vector<Particle *> particlesToDelete {};
	for (Particle* particle : m_DigParticles) {
		particle->Update(elapsedTime);
		if (particle->IsDead()) {
			particlesToDelete.push_back(particle);
		}
	}
	for (Particle* particle : particlesToDelete) {
		m_DigParticles.erase(std::remove(m_DigParticles.begin(), m_DigParticles.end(), particle), m_DigParticles.end());
		delete particle;
	}

	m_SmokeTimer += elapsedTime;
	if (m_SmokeTimer >= m_SmokeTime) {
		m_SmokeTimer = 0.0f;
		Vector2f Dir { static_cast<float>(m_Direction == PlayerDirection::Left ? 60 : -60), 20 };
		Particle* NewSmokeParticle = new Particle(m_OutletPos + m_Position, Dir, Vector2f { 0.0f, 9.81f * 5}, 1.f, TextureManager::GetInstance()->GetTexture("particles/smoke.png"));
		NewSmokeParticle->SetFlipped(m_Direction == PlayerDirection::Left);
		m_SmokeParticles.push_back(NewSmokeParticle);
	}
	std::vector<Particle*> smokeParticlesToDelete{};
	for (Particle* particle : m_SmokeParticles) {
		particle->Update(elapsedTime);
		if (particle->IsDead()) {
			smokeParticlesToDelete.push_back(particle);
		}
	}
	for (Particle* particle : smokeParticlesToDelete) {
		m_SmokeParticles.erase(std::remove(m_SmokeParticles.begin(), m_SmokeParticles.end(), particle), m_SmokeParticles.end());
		delete particle;
	}


	//check for keys
	if (m_State != PlayerState::Digging) {
		if (utils::isKeyDown(SDL_SCANCODE_W)) {
			m_State = PlayerState::Flying;
			// m_Vel.y = m_Speed / 10;
			m_Acc.y += m_Speed * 10;
			if (!m_IsPropellorDeployed) {
				m_CurrentAnimation = m_FlyStartAnimation;
				m_FlyStartAnimation->SetFlipped(m_Direction == PlayerDirection::Right);
			}
			else {
				m_CurrentAnimation = m_FlyAnimation;
			}
			m_Grounded = false;
		}
		if (utils::isKeyPressed(SDL_SCANCODE_S)) {
			if (m_Grounded) {
				if (this->CanDig(Collision::Bottom, level)) {
					m_DigDirection = DigDirection::Down;
					m_CurrentAnimation = m_DigStartAnimation;
					m_CurrentAnimation->Reset();
					m_IsDiggingPrimed = false;
					this->Dig(Collision::CollisionDirection::Bottom, level);
				}
			}
		}
		if (utils::isKeyDown(SDL_SCANCODE_A)) {
			if (!m_IsTurning) {
				m_WalkAnimation->SetFlipped(false);
				m_FlyAnimation->SetFlipped(false);
			}
			m_Acc.x = -m_Speed;
			if (m_Direction == PlayerDirection::Right) {
				m_IsTurning = true;
				m_CurrentAnimation = m_State == PlayerState::Walking ? m_TurnAnimation : m_FlyTurnAnimation;
				m_CurrentAnimation->SetFlipped(true);
				m_CurrentAnimation->Reset();
			}
			m_Direction = PlayerDirection::Left;
			if (m_Grounded && !m_DidJustDigLeft) {
				//Check if the player doesnt come from digging a tile
				if (this->CanDig(Collision::CollisionDirection::Left, level)) {
					m_DigDirection = DigDirection::Left;
					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)) {
			if (!m_IsTurning) {
				m_WalkAnimation->SetFlipped(true);
				m_FlyAnimation->SetFlipped(true);
			}
			m_Acc.x = m_Speed;

			if (m_Direction == PlayerDirection::Left) {
				m_IsTurning = true;
				m_CurrentAnimation = m_State == PlayerState::Walking ? m_TurnAnimation : m_FlyTurnAnimation;
				m_CurrentAnimation->SetFlipped(false);
				m_CurrentAnimation->Reset();
			}

			m_Direction = PlayerDirection::Right;
			if (m_Grounded && !m_DidJustDigRight) {
				//Check if the player doesnt come from digging a tile
				if (this->CanDig(Collision::CollisionDirection::Right, level)) {
					m_DigDirection = DigDirection::Right;
					this->Dig(Collision::CollisionDirection::Right, level);
					m_DidJustDigRight = true;
				}
			}
		}
		if (m_DidJustDigRight) {
			if (!utils::isKeyDown(SDL_SCANCODE_D)) {
				m_DidJustDigRight = false;
			}
		}

		m_Vel = m_Vel + m_Gravity * elapsedTime;
		m_Vel = m_Vel + m_Acc * elapsedTime;
		m_Vel = utils::clamp(m_Vel, Vector2f { -m_Speed, -m_Speed }, Vector2f { m_Speed, m_Speed });

		//air resistance
		//only if not moving
		if (abs(m_Acc.x) < 0.1f) {
			m_Vel.x = m_Vel.x * 0.90f;
		}

		m_Acc = Vector2f { 0, 0 };


		m_CurrentAnimation->Update(elapsedTime);

		if (m_State == PlayerState::Flying && m_Grounded) {
			m_State = PlayerState::Idle;
			m_WalkAnimation->SetFlipped(m_Direction == PlayerDirection::Right);
			m_CurrentAnimation = m_WalkAnimation;
			m_IsPropellorDeployed = false;
			m_FlyStartAnimation->Reset();


		}

		if (m_CurrentAnimation->IsDone() && m_IsTurning) {
			m_CurrentAnimation = m_State == PlayerState::Walking ? m_WalkAnimation : m_FlyAnimation;
			m_IsTurning = false;
		}

		if (m_CurrentAnimation == m_FlyStartAnimation) {
			if (m_FlyStartAnimation->IsDone()) {
				m_IsPropellorDeployed = true;
				m_CurrentAnimation = m_FlyAnimation;
			}
			else {
				m_CurrentAnimation = m_FlyStartAnimation;
			}
		}

		if (m_Direction == PlayerDirection::Left) {
			m_OutletPos = m_OutLeftPos;
		}
		else {
			m_OutletPos = m_OutRightPos;
		}
#pragma region Collision
		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;
		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() != GroundTileTypeManager::GetInstance()->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();
			Collision::ResolvePlayerVsRect(*this, elapsedTime, &rect);
		}
#pragma endregion

		if (m_State == PlayerState::Walking || m_State == PlayerState::Idle) { //Fix for when the state is JUST set to digging
			if (std::abs(m_Vel.x) < 0.1f) {
				m_State = PlayerState::Idle;
			}
			else {
				m_State = PlayerState::Walking;
			}
		}
	}
	switch (m_State) {
	case PlayerState::Flying:
		GameManager::GetInstance().DecreaseFuel(0.06f);
		ChangeSound(m_FlySound);
		break;
	case PlayerState::Idle:
		m_WalkAnimation->SetPlaying(false);
		GameManager::GetInstance().DecreaseFuel(0.02f);
		ChangeSound(m_IdleSound);

		break;
	case PlayerState::Walking:
		m_WalkAnimation->SetPlaying(true);
		GameManager::GetInstance().DecreaseFuel(0.04f);
		ChangeSound(m_WalkSound);

		break;
	case PlayerState::Digging: {
		// m_walkAnimation->SetPlaying(false);
		GameManager::GetInstance().DecreaseFuel(0.06f);
		ChangeSound(m_DigSound);
		//Diganimation
		m_CurrentAnimation->Update(elapsedTime);
		if (m_CurrentAnimation->IsDone() && m_State == PlayerState::Digging && !m_IsDiggingPrimed) {
			m_IsDiggingPrimed = true;
			m_CurrentAnimation = m_DigAnimation;
		}

		if (m_IsDiggingPrimed) {
			if (!m_Digging) {
				m_Digging = true;
				m_DigStart = m_Position;
				m_Vel = Vector2f { 0, 0 };
			}

			m_DigProgress += elapsedTime;
			//lerp to the destination
			float progress = utils::map(m_DigProgress, 0.0f, m_DigTime, 0.0f, 1.0f);
			int particleProgress = (int)utils::map(m_DigProgress, 0.0f, m_DigTime, 0.0f, 100.0f);
			if (particleProgress % 2 == 0) {
				m_DigParticles.push_back(new Particle(m_Position + Vector2f { 20, 0 }, Vector2f { (float)utils::randRange(-200, 200), (float)utils::randRange(-100, -300) },Vector2f { 0.0f, -9.81f * 20}, 5.f,
				                                      TextureManager::GetInstance()->GetTexture("particles/dirt_" + std::to_string(utils::randRange(1, 8)) + ".png")));
			}
			m_Position = utils::lerp(m_DigStart, m_DigDestination, progress);
			if (progress >= 0.5f && !m_HasDeletedTile) {
				m_DigTile->SetTileType(GroundTileTypeManager::GetInstance()->AIR);
				m_DigTile = nullptr;
				m_HasDeletedTile = true;
			}
			if (progress >= 1.0f) {
				m_State = PlayerState::Idle;
				m_CurrentAnimation = m_WalkAnimation;
				m_HasDeletedTile = false;
				m_Digging = false;
				GameManager::GetInstance().IncreaseScore(m_ToAddPoints);
				m_ToAddPoints = 0;

				//Add the dug item to the inventory
				PlayerInventory* inventory = GameManager::GetInstance().GetInventory();
				InventoryItem item = inventory->GetItemByType(m_ToAddTile);
				ItemStack stack = ItemStack { item, 1 };
				inventory->AddItem(stack);

				std::cout << "Added: " << PlayerInventory::GetItemName(item) << std::endl;

				//Print the inventory
				std::cout << "-----------------------" << std::endl;
				std::cout << "Inventory: " << std::endl;
				std::vector<ItemStack *> items = inventory->GetItems();
				for (ItemStack* i : items) {
					std::cout << PlayerInventory::GetItemName(i->m_ItemType) << " Quantity: " << i->m_Quantity << std::endl;
				}

				std::cout << "-----------------------" << std::endl;

			}
		}

		break;
	}
	default:
		break;
	}

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

	if (m_DidSoundChange) {
		m_CurrentSound->Stop();
		m_DidSoundChange = false;
	}
	if (m_CurrentSound != nullptr) {
		if (!m_CurrentSound->IsPlaying()) {
			m_CurrentSound->Play(1);
		}
	}

}
