using System.Numerics;
using Raylib_cs;

namespace Tiles;

public class Game
{
    const int _tileSize = 8;
    const int _worldWidth = 1920/8;
    const int _worldHeight = 1080/8;
    
    private int _screenWidth;
    private int _screenHeight;

    private Dictionary<string, Tile> _tiles = new();
    private Dictionary<Vector2, string> _worldGrid = new();
    
    public Game(int screenWidth, int screenHeight)
    {
        _screenWidth = screenWidth;
        _screenHeight = screenHeight;
        Raylib.InitWindow(_screenWidth, _screenHeight, "Tiles");
        Raylib.SetTargetFPS(60);

        SetupTiles();
        
        GenerateWorld();

        while (!Raylib.WindowShouldClose())
        {
            Raylib.BeginDrawing();
            Raylib.ClearBackground(new Color(20, 70, 100, 255));
            
            DrawWorld();
            
            Raylib.EndDrawing();
        }
    }

    private void SetupTiles()
    {
        _tiles.Add("dirt", new("dirt", "data/tiles/images/dirt.png"));
        _tiles.Add("grass", new("grass", "data/tiles/images/grass.png"));
        _tiles.Add("rock", new("rock", "data/tiles/images/rock.png"));
    }

    private void DrawWorld()
    {
        foreach (var tile in _worldGrid)
        {
            if (tile.Value == "air")
            {
                Raylib.DrawRectangle((int)tile.Key.X * _tileSize,(int)tile.Key.Y * _tileSize, _tileSize, _tileSize, new(0,0,0,0));
            }
            else
            {
                Raylib.DrawTexture(_tiles[tile.Value].Texture, (int)tile.Key.X * _tileSize,(int)tile.Key.Y * _tileSize, Color.White);
            }
        }
    }
    

    // private void GenerateWorld()
    // {
    //     for (int x = 0; x < _worldWidth; x++)
    //     {
    //         for (int y = 0; y < _worldHeight; y++)
    //         {
    //             _worldGrid.Add(new(x, y), "dirt");
    //         }
    //     }
    // }
    
    private void GenerateWorld()
    {
        int totalHeight = _worldHeight;

        int grassHeight = (int)(totalHeight * 0.05);
        int dirtHeight = (int)(totalHeight * 0.10);
        int airHeight = (int)(totalHeight * 0.50);
        int rockHeight = totalHeight - (airHeight + grassHeight + dirtHeight);

        for (int x = 0; x < _worldWidth; x++)
        {
            for (int y = 0; y < totalHeight; y++)
            {
                string tileType;

                if (y < airHeight)
                    tileType = "air";
                else if (y < airHeight + grassHeight)
                    tileType = "grass";
                else if (y < airHeight + grassHeight + dirtHeight)
                    tileType = "dirt";
                else
                    tileType = "rock";

                _worldGrid.Add(new(x, y), tileType);
            }
        }
    }
}