package com.moka.gdtauto.util;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;

import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.moka.gdtauto.config.RobotConfig;

import lombok.AllArgsConstructor;


@Component
@AllArgsConstructor
public class RobotUtil {

    private final RobotConfig robotConfig;


    private static final Map<String , BiFunction<String, String, String>> robotPush = new HashMap<>();
    private static final String qywx_msg_template  = """
            {"msgtype": "markdown","markdown": {"content": "%s"}}
            """;

    private static final String feishu_msg_template  = """
            {"msg_type":"text","content":{"text":"%s"}}
            """;
    static {
        robotPush.put("qywx", (url, msg) -> {
            String s = String.format(qywx_msg_template, msg);
            try (HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .followRedirects(HttpClient.Redirect.NORMAL)
                .build()) {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Accept", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(s))
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            return response.body();
           } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
           }
        }
        );

        robotPush.put("feishu", (url,msg) -> {
            String s = String.format(feishu_msg_template, msg);
            try (HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .followRedirects(HttpClient.Redirect.NORMAL)
                .build()) {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Accept", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(s))
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            return response.body();
           } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
           }
        });
    }

    public String pushMsg(List<String> msgs) {
        String type = robotConfig.getType();
        List<List<String>> partitions = Lists.partition(msgs, 10);
        partitions.forEach(msg -> {
            robotPush.get(type).apply(robotConfig.getUrl(), String.join("\n", msg));
        });
        return "ok";
    }
}
