package com.uca.dao;

import com.uca.entity.PokedexEntity;
import com.uca.exceptions.ServiceException;

import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;

public class PokedexDAO {
    public PokedexEntity getById(int id) throws ServiceException {
        if (id < 0 || id > 1008) {
            throw new IllegalArgumentException("This number is not in the Pokédex");
        }

        try {
            URL url = new URL(String.format("https://pokeapi.co/api/v2/pokemon/%d", id));
            HttpURLConnection pokemonConnection = this.getConnectionByURL(url);

            url = new URL(String.format("https://pokeapi.co/api/v2/pokemon-species/%d", id));
            HttpURLConnection speciesConnection = this.getConnectionByURL(url);

            return parseFromJSON(resultToJSON(pokemonConnection), resultToJSON(speciesConnection));
        } catch (MalformedURLException e) {
            throw new ServiceException("Erreur lors de la création de l'URL");
        } catch (ServiceException e) {
            throw new RuntimeException(e);
        }
    }

    private HttpURLConnection getConnectionByURL(URL url) throws ServiceException {
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
                throw new IllegalArgumentException("L'URL " + url + " n'est pas valide");
            }

            return connection;
        } catch (IOException e) {
            throw new ServiceException("Erreur dans la récupération des données");
        }
    }

    private JSONObject resultToJSON(HttpURLConnection connection) throws ServiceException {
        try {
            StringBuilder jsonString = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                jsonString.append(line);
            }

            return new JSONObject(jsonString.toString());
        } catch (IOException e) {
            throw new ServiceException("Erreur lors de la lecture des données de l'API");
        }
    }

    private PokedexEntity parseFromJSON(JSONObject pokemon, JSONObject species) {
        PokedexEntity pokedex = new PokedexEntity();

        // Identifiant du Pokémon dans le Pokédex
        pokedex.setId(pokemon.getInt("id"));

        // Nom du Pokémon en français (indice 4 dans l'API)
        pokedex.setName(species.getJSONArray("names").getJSONObject(4).getString("name"));

        // Sprite du Pokémon
        pokedex.setSpriteURL(pokemon.getJSONObject("sprites").getString("front_default"));

        return pokedex;
    }
}
