using System.Text.Json;
using Newtonsoft.Json;
using Raylib_cs;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace Tiles;

public class Tile
{
    public string Name { get; private set; }
    public string ImagePath { get; private set; }
    public Image Image { get; private set; }
    public Texture2D Texture { get; private set; }
    public bool Transparent { get; private set; }

    private static JsonSerializerOptions _jsonSerializerOptions = new()
    {
        WriteIndented = true
    };

    public static Tile GenerateTileFromJson(string jsonPath)
    {
        try
        {
            var json = File.ReadAllText(jsonPath);
            var tileData = JsonSerializer.Deserialize<TileData>(json);
            
            if (tileData == null) throw new Exception($"Could not deserialize tile data from {jsonPath}");

            var tile = new Tile()
            {
                Name = tileData.Name,
                ImagePath = tileData.ImagePath,
                Transparent = tileData.Transparent,
            };
            
            tile.Image = tile.LoadImage(tile.ImagePath);
            tile.Texture = tile.LoadTexture(tile.Image);
            
            return tile;
        }
        catch (Exception e)
        {
            Console.WriteLine($"Error loading tile from {jsonPath}: {e.Message}");
            throw;
        }
    }
    
    public static void GenerateTileJson(string outputDir, string name, string imagePath, bool transparent = false)
    {
        var tile = new TileData()
        {
            Name = name,
            ImagePath = imagePath,
            Transparent = transparent
        };
        
        string json = JsonSerializer.Serialize(tile, _jsonSerializerOptions);

        File.WriteAllText(outputDir + name + ".json", json);
        Console.WriteLine($"Tile JSON saved to {outputDir + name + ".json"}");
    }

    private Image LoadImage(string path)
    {
        try
        {
            Image img = Raylib.LoadImage(path);
            return img;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    private Texture2D LoadTexture(Image img)
    {
        try
        {
            var texture = Raylib.LoadTextureFromImage(img);
            return texture;
        }
        catch (Exception e)
        {
            Console.WriteLine($"Failed to load texture: {e}");
            throw;
        }
    }
}

[Serializable]
public class TileData
{
    public string Name { get; set; }
    public string ImagePath { get; set; }
    public bool Transparent { get; set; }   
}