package com.xeovalyte.polarcraft.util;

import com.xeovalyte.polarcraft.PolarcraftMod;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;

public class verifyFunction {
    public static void onPlayerJoin(ServerPlayerEntity player, MinecraftServer server) {
        UUID uuid = player.getUuid();

        try {
            URL url = new URL(PolarcraftMod.configVerifyUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            String requestBody = "{\"uuid\":\"" + uuid + "\"}";

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(requestBody.getBytes());
            outputStream.flush();
            outputStream.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            Gson gson = new Gson();
            JsonElement element = gson.fromJson(response.toString(), JsonElement.class);
            JsonObject jsonResponse = element.getAsJsonObject();

            boolean verified = jsonResponse.get("verified").getAsBoolean();

            if (!verified) {
                int code = jsonResponse.get("code").getAsInt();
                
                player.networkHandler.disconnect(Text.literal("Whitelist yourself by using this code: " + code));
            } else {
                server.getCommandManager().executeWithPrefix(server.getCommandSource(), "/lp user " + player.getUuid() + " meta set display " + "\"" + jsonResponse.get("username").getAsString() + "\"");

                messageFunctions.sendGameMessage(player.getUuid(), jsonResponse.get("usernameWithoutStyle").getAsString() + " joined the game");
            }
        } catch (IOException e) {
            player.networkHandler.disconnect(Text.literal("There was an error while verifing your account"));
            e.printStackTrace();
        }
    }

}
