package eu.mhsl.minenet.minigames.command.privileged;

import com.google.gson.Gson;
import eu.mhsl.minenet.minigames.command.PrivilegedCommand;
import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.score.tournament.TournamentDisplay;
import net.minestom.server.entity.Player;

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

public class PublishRewardCommand extends PrivilegedCommand {
    private final HttpClient rewardPublishClient = HttpClient.newHttpClient();
    public PublishRewardCommand() {
        super("publishReward");

        setDefaultExecutor((sender, context) -> {
            try {
                Room room = Room.getRoom((Player) sender).orElseThrow();
                TournamentDisplay world = new TournamentDisplay(room.getTournament());
                room.moveMembersToInstance(world);

                String rewardRequestJson = new Gson().toJson(room.getTournament().getRewards());
                HttpRequest giveRewardsRequest = HttpRequest.newBuilder()
                        .uri(new URI("http://10.20.7.1:8080/api/event/reward"))
                        .POST(HttpRequest.BodyPublishers.ofString(rewardRequestJson))
                        .build();

                room.getTournament().getRewards();
                HttpResponse<Void> rawResponse = rewardPublishClient.send(giveRewardsRequest, HttpResponse.BodyHandlers.discarding());
                sender.sendMessage(String.format("Rewards published: HTTP %s", rawResponse.statusCode()));
            } catch (Exception e) {
                sender.sendMessage(e.getMessage());
            }
        });
    }
}
