#include "TileMapManager.h"
#include <iostream>

TileMapManager::TileMapManager()
{
}

void TileMapManager::CreateMap(const std::string& name, 
                               int widthInChunks, 
                               int heightInChunks)
{
    if (name.empty())
    {
        std::cerr << "[TileMapManager] Error: Map name cannot be empty\n";
        return;
    }
    if (widthInChunks <= 0 || heightInChunks <= 0)
    {
        std::cerr << "[TileMapManager] Error: Map dimensions must be positive\n";
        return;
    }
    
    // Create and store map
    maps.emplace(name, TileMap(name, widthInChunks, heightInChunks));
    
    // If this is the first map -- make it current
    if (currentMapName.empty())
    {
        currentMapName = name;
        std::cout << "[TileMapManager] Created and set as current: " << name << "\n";
    }
    else
    {
        std::cout << "[TileMapManager] Created map: " << name << "\n";
    }
}

// Returns pointer to a map or nullptr
TileMap* TileMapManager::GetMap(const std::string& name)
{
    auto it = maps.find(name);
    if (it == maps.end())
    {
        return nullptr;
    }
    return &it->second;
}

const TileMap* TileMapManager::GetMap(const std::string& name) const
{
    auto it = maps.find(name);
    if (it == maps.end())
    {
        return nullptr;
    }
    return &it->second;
}

// Returns current map or nullptr
TileMap* TileMapManager::GetCurrentMap()
{
    return GetMap(currentMapName);
}

const TileMap* TileMapManager::GetCurrentMap() const
{
    return GetMap(currentMapName);
}

// Switch active map (returns true on success)
bool TileMapManager::SetCurrentMap(const std::string& name)
{
    if (!HasMap(name))
    {
        std::cerr << "[TileMapManager] Error: Map " << name << " not found\n";
        return false;
    }
    if (currentMapName == name)
    {
        std::cout << "[TileMapManager] Map " << name << " already loaded\n";
        return true;
    }
    
    currentMapName = name;
    std::cout << "[TileMapManager] Map " << name << " loaded\n";
    return true;
}

// Returns list of all map names
std::vector<std::string> TileMapManager::GetAllMapNames() const
{
    std::vector<std::string> names;
    names.reserve(maps.size());
    for (const auto& pair : maps)
    {
        names.push_back(pair.first);
    }
    return names;
}

// Check if map exists
bool TileMapManager::HasMap(const std::string& name) const
{
    return maps.find(name) != maps.end();
}

// Prints all maps and current map
void TileMapManager::PrintAllMaps() const
{
    // TODO: Later
}