#include "pch.h"
#include "WorldGridManager.h"

#include <stdexcept>

#include "WorldTile.h"

WorldGridManager::WorldGridManager() {
	for (size_t x { 0 }; x < WORLD_WIDTH; ++x) {
		for (size_t y { 0 }; y < WORLD_HEIGHT; ++y) {
			m_worldTiles[x][y] = nullptr;
		}
	}

}
WorldGridManager::~WorldGridManager() {

}
surroundingTiles WorldGridManager::GetSurroundingTiles(const WorldTile* world_tile) {
	surroundingTiles tiles;
	Vector2f pos = world_tile->GetPosition();
	Vector2f gridCoords = this->GetIndexFromPosition(pos);
	int x = gridCoords.x;
	//TODO: Stupid fix, fix this
	int y = gridCoords.y - 1;

	tiles.SetTile(TileDirection::TopLeft, this->GetTileAtIndex(x - 1, y - 1));
	tiles.SetTile(TileDirection::TopMiddle, this->GetTileAtIndex(x, y - 1));
	tiles.SetTile(TileDirection::TopRight, this->GetTileAtIndex(x + 1, y - 1));

	tiles.SetTile(TileDirection::MiddleLeft, this->GetTileAtIndex(x - 1, y));
	tiles.SetTile(TileDirection::MiddleRight, this->GetTileAtIndex(x + 1, y));

	tiles.SetTile(TileDirection::BottomLeft, this->GetTileAtIndex(x - 1, y + 1));
	tiles.SetTile(TileDirection::BottomMiddle, this->GetTileAtIndex(x, y + 1));
	tiles.SetTile(TileDirection::BottomRight, this->GetTileAtIndex(x + 1, y + 1));

	return tiles;
	
}
Vector2f WorldGridManager::GetIndexFromPosition(Vector2f position) {
	int x = int(position.x / TILE_WIDTH + WORLD_WIDTH / 2);
	int y = int(-position.y / TILE_HEIGHT);
	return Vector2f{ float(x), float(y) };
}
WorldTile * WorldGridManager::GetTileAtIndex(const int x, const int y) const {
	if (x < 0 || x >= WORLD_WIDTH || y < 0 || y >= WORLD_HEIGHT) {
		return nullptr;
		//TODO: see if this can be Math'ed out
	}
	return m_worldTiles[x][y];
}
WorldTile * WorldGridManager::GetTileAtWorldPos(const Vector2f& pos) const {
	int x = int(pos.x / TILE_WIDTH + WORLD_WIDTH / 2);
	int y = int(-pos.y / TILE_HEIGHT);
	if (x < 0 || x >= WORLD_WIDTH || y < 0 || y >= WORLD_HEIGHT) {
		return nullptr;
	}
	return m_worldTiles[x][y];
}
void WorldGridManager::SetTileAtIndex(const int x, const int y, WorldTile* tile) {
	m_worldTiles[x][y] = tile;
}
