using Godot;
using System;
using System.ComponentModel;
using System.Text;
using Godot.Sharp.Extras;
using PokeApiNet;
using PokePurple.Library.Singletons;

public partial class WildPokemon : Node2D
{
    private Generations _generations = new();
    private Pokemon _pokemon;
    private PokeApiClient _apiClient;
    private System.Net.Http.HttpClient _http;
    [NodePath] private AnimatedSprite2D _pokemonSprite;

    private String _animatedUrl =
        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/showdown/{0}.gif";

    public override void _Ready()
    {
        this.OnReady();
        _apiClient = new();
        _http = new();
        _generations.Generation = 8;
        InitPokemon();
    }

    public override void _Input(InputEvent @event)
    {
        if (Input.IsActionJustPressed("debug_pokemon"))
        {
            InitPokemon();
        }
    }

    private async void InitPokemon()
    {
        var pokeId = _generations.PickRandomPokemon();
        _pokemon = await _apiClient.GetResourceAsync<Pokemon>(pokeId);
        GD.Print(_pokemon.Name);
        var url = String.Format(_animatedUrl, pokeId);
        GD.Print(url);
        var data = await _http.GetByteArrayAsync(url);
        var frames = GifManager.Instance.SpriteFramesFromBuffer(data);
        _pokemonSprite.SpriteFrames = frames;
        _pokemonSprite.Play();
    }
}
