package com.ecep.contract.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

public class HttpJsonUtils {
    public static void post(String url,
                            Consumer<Map<String, Object>> data,
                            Consumer<JsonNode> consumer,
                            ObjectMapper objectMapper, Proxy proxy) throws IOException {

        HashMap<String, Object> params = new HashMap<>();
        data.accept(params);
        URI uri = URI.create(url);
        HttpURLConnection conn = (HttpURLConnection) (proxy == null ? uri.toURL().openConnection() : uri.toURL().openConnection(proxy));
        conn.usingProxy();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        PrintWriter writer = new PrintWriter(conn.getOutputStream());
        objectMapper.writeValue(writer, params);
        writer.flush();
        conn.connect();
        try (InputStream is = conn.getInputStream()) {
            JsonNode json = objectMapper.readTree(is);
            consumer.accept(json);
        }

    }

    public static void get(String url, Consumer<JsonNode> consumer, ObjectMapper objectMapper, Proxy proxy) throws IOException {
        URI uri = URI.create(url);
        HttpURLConnection conn = (HttpURLConnection) (proxy == null ? uri.toURL().openConnection() : uri.toURL().openConnection(proxy));
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json, text/plain, */*");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36");
        try (InputStream is = conn.getInputStream()) {
            JsonNode json = objectMapper.readTree(is);
            consumer.accept(json);
        }
    }
}
