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

TileRenderer::TileRenderer(SDL_Renderer* renderer) : renderer(renderer)
{
}

void TileRenderer::SetTileset(SDL_Texture* texture, int tileSizePx)
{
    tileset = texture;
    tileSize = tileSizePx;
}

void TileRenderer::RenderVisibleChunks(TileMap* map,
                                       int cameraX, int cameraY,
                                       int screenWidth, int screenHeight)
{
    if (!map || !tileset || !renderer)
    {
        return;
    }
    
    auto visibleChunks = map->GetVisibleChunks(cameraX, cameraY, screenWidth, screenHeight);
    
    for (Chunk* chunk : visibleChunks)
    {
        if (!chunk)
        {
            continue;
        }
        
        int chunkWorldX = chunk->chunkX * CHUNK_SIZE * tileSize;
        int chunkWorldY = chunk->chunkY * CHUNK_SIZE * tileSize;
        
        // Draw TileMap
        // TODO: Add layers to chunks later
        for (int ly = 0; ly < CHUNK_SIZE; ++ly)
        {
            for (int lx = 0; lx < CHUNK_SIZE; ++lx)
            {
                const Tile& tile = chunk->GetTile(lx, ly);
                if (tile.tileId == 0) // Do not draw tile with id 0
                {
                    continue;
                }
                
                int screenX = chunkWorldX + lx * tileSize - cameraX;
                int screenY = chunkWorldY + ly * tileSize - cameraY;
                
                // Simple culling
                if (screenX + tileSize < 0 || screenX > screenWidth ||
                    screenY + tileSize < 0 || screenY > screenHeight)
                {
                    continue;
                }
                
                // Assuming 16 tiles per row
                int srcX = static_cast<int>(tile.tileId % 16) * tileSize;
                int srcY = static_cast<int>(tile.tileId / 16) * tileSize;
                
                SDL_Rect srcRect = {               // Get tile from tileset
                    srcX, srcY, 
                    tileSize, tileSize
                };
                
                SDL_Rect dstRect = {               // Put tile into screen
                    screenX, screenY,
                    tileSize, tileSize
                };
                
                SDL_RenderCopy(renderer, tileset, &srcRect, &dstRect);
            }
        }
    }
}