package com.example.application.api;

import com.nimbusds.jose.shaded.gson.*;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.*;

public class ApiRedmine {
    private static final String REDMINE_URL = "http://localhost:3000";
    private static final String API_KEY = "cf3be6168e66c99892c6212ea0bc64e8ab1c6848";
    public static final Gson GSON = new Gson();

    public static String createIssue(Map<String, String> issueDetails) {
        Map<String, Object> payload = new HashMap<>();
        payload.put("issue", issueDetails);
        String jsonPayload = GSON.toJson(payload);

        try {
            //Crear la solicitud HTTP POST
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(REDMINE_URL + "/issues.json"))
                    .header("Content-Type", "application/json")
                    .header("X-Redmine-API-Key", API_KEY)
                    .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
                    .build();

            //Enviar la solicitud
            HttpClient client = HttpClient.newHttpClient();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            return response.body();
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: "+e.getMessage();
        }
    }

    public List<String> getTicketTypes() {
        List<String> ticketTypes = new ArrayList<>();
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(REDMINE_URL + "/trackers.json"))
                .header("Content-Type", "application/json")
                .header("X-Redmine-API-Key", API_KEY)
                .build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                String responseBody = response.body();
                ticketTypes = parseTicketTypes(responseBody);
            } else {
                System.err.println("Error en la respuesta: " + response.statusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ticketTypes;
    }

    private List<String> parseTicketTypes(String json) {
        List<String> names = new ArrayList<>();
        JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
        JsonArray trackers = jsonObject.getAsJsonArray("trackers");
        for (JsonElement trackerElement : trackers) {
            JsonObject tracker = trackerElement.getAsJsonObject();
            String name = tracker.get("name").getAsString();
            names.add(name);
        }
        return names;
    }
}
