package tech.nevets.tvpn;

import tech.nevets.jconf.JsonConfig;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

public class Utils {
    private static final Logger LOGGER = new Logger(Utils.class);

    public static final String WG_CONF_DIR = "C:\\Program Files\\WireGuard\\Data\\Configurations\\";
    public static final File APP_DIR = new File("C:\\Program Files\\TVPN\\");
    public static final JsonConfig CONFIG = new JsonConfig(APP_DIR + "/config.json", getConfStr());
    public static final String API_ENDPOINT_BASE = CONFIG.getString("apiEndpoint");

    static {
        if (!APP_DIR.exists()) APP_DIR.mkdirs();
    }

    private static String getConfStr() {
        return """
                {
                    "apiEndpoint":"http://tvpn.lan"
                }
                """;
    }

    public static String get(URI url, Map<String, String> headers) {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest.Builder reqBuilder = HttpRequest.newBuilder()
                .GET()
                .uri(url);
        return req(headers, client, reqBuilder);
    }

    public static String post(URI url, Map<String, String> headers, HttpRequest.BodyPublisher bodyPub) {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest.Builder reqBuilder = HttpRequest.newBuilder()
                .POST(bodyPub)
                .uri(url);
        return req(headers, client, reqBuilder);
    }

    private static String req(Map<String, String> headers, HttpClient client, HttpRequest.Builder reqBuilder) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            reqBuilder.header(header.getKey(), header.getValue());
        }
        HttpRequest req = reqBuilder.build();
        HttpResponse<String> res;
        try {
            res = client.send(req, HttpResponse.BodyHandlers.ofString());
            return res.body();
        } catch (IOException | InterruptedException e) {
            LOGGER.error(e.getMessage());
            return "";
        }
    }

    public static void throwException() throws RuntimeException {
        throw new RuntimeException("Yay an exception!");
    }
}
