/*
 * Copyright (C) 2025  Tim Zimmermann <tim@aglais.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.aglais.zms.gbif;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * Class for interacting with the GBIF API
 */
public class GBIFAPI {

    private static final String API_URL = "https://api.gbif.org/v1";
    private static final Gson GSON = new Gson();

    private static <T> T readURL(String url, Class<T> jsonClass) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) URI.create(url).toURL().openConnection();

        conn.setDoOutput(true);
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            return GSON.fromJson(reader, jsonClass);
        }
    }

    /**
     * Matches a species name against the GBIF species database using the GBIF API.
     *
     * @param name The name of the species to match.
     * @return A GBIFSpeciesMatch object containing the details of the matched species.
     * @throws IOException If an error occurs during the HTTP request.
     */
    public static GBIFSpeciesMatch matchSpecies(String name) throws IOException {
        return readURL(API_URL + "/species/match?name=" + URLEncoder.encode(name, StandardCharsets.UTF_8),
                GBIFSpeciesMatch.class);
    }

    /**
     * Retrieves the IUCN Red List category for a species using its usage key from the GBIF API.
     *
     * @param usageKey The usage key of the species whose IUCN Red List category is being retrieved.
     * @return A GBIFSpeciesIUCNRedListCategory object containing details of the species' IUCN Red List category.
     * @throws IOException If an error occurs during the HTTP request to the GBIF API.
     */
    public static GBIFSpeciesIUCNRedListCategory getSpeciesIUCNRedListCategory(int usageKey) throws IOException {
        return readURL(API_URL + "/species/" + usageKey + "/iucnRedListCategory",
                GBIFSpeciesIUCNRedListCategory.class);
    }

}
