package com.yutou.bilibili.Tools;

import com.alibaba.fastjson.JSONObject;
import com.yutou.bilibili.interfaces.NetworkInterface;

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.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Set;

public class HttpTools {
    public static String get(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestProperty("User-Agent", getKuKuUA());
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder str = new StringBuilder();
            String tmp;
            while ((tmp = reader.readLine()) != null) {
                str.append(tmp);
            }
            reader.close();
            connection.disconnect();
            return str.toString();
        } catch (Exception e) {
            com.yutou.bilibili.Tools.Log.e(e);
        }
        return null;
    }

    public synchronized static void post(final String url, final byte[] body, final NetworkInterface networkInterface) {

        new Thread(new Runnable() {

            @Override
            public void run() {
                String tmp;
                StringBuilder str = new StringBuilder();
                try {
                    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setRequestMethod("POST");
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setConnectTimeout(5 * 1000);
                    connection.setReadTimeout(10 * 1000);
                    connection.addRequestProperty("Connection", "keep-alive");
                    connection.addRequestProperty("Accept", "*/*");
                    connection.addRequestProperty("User-Agent", getExtUa());
                    //connection.addRequestProperty("content-type", "application/json");
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    connection.addRequestProperty("charset", "UTF-8");
                    OutputStream outputStream = connection.getOutputStream();

                    outputStream.write(body);
                    outputStream.write("\n".getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    while ((tmp = reader.readLine()) != null) {
                        str.append(tmp);
                    }

                     //  com.yutou.bilibili.Tools.Log.i( "[" + url + "?" + new String(body,StandardCharsets.UTF_8) + "]body:" + str + " (" + connection.getResponseCode() + ")");
                    if (networkInterface != null) {
                        try {
                            networkInterface.httpGetData(str.toString(), connection.getResponseCode());
                        } catch (IOException e) {
                            com.yutou.bilibili.Tools.Log.e(e);
                        }
                        networkInterface.onCookie(connection.getHeaderField("Set-Cookie"));
                    }
                    connection.disconnect();
                    outputStream.close();
                    reader.close();
                } catch (Exception e) {
                   networkInterface.httpError(e);
                }
            }
        }).start();
    }

    private static String getExtUa() {
        return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36";
    }

    private static String getKuKuUA() {
        return "/KUKU_APP(Android/#/cn.kuku.sdk/ttsdk17228/29401/A-2.9.4.01.KUSDK/868139039134314/fcddf839c8c135fa/F4:60:E2:AB:25:1A/460019406520644/+8618569400341/#/9/Redmi 6 Pro/xiaomi/1736/76fda4d6-cd6b-485f-987b-8d347b007f24/#/KUKU/Native/92972ea9651fbd2e)";
    }

    public static String toUrlParams(JSONObject json) {
        StringBuilder string = new StringBuilder();
        Set<String> keys = json.keySet();
        for (String key : keys) {
            try {
                string.append("&").append(key).append("=").append(URLEncoder.encode(json.getString(key), "UTF-8"));
            } catch (Exception e) {
                com.yutou.bilibili.Tools.Log.e(e);
                try {
                    string.append("&").append(URLEncoder.encode(key, "UTF-8")).append("=");
                    //    string += "&" + key + "=";
                } catch (Exception e1) {
                    string.append("&").append(key).append("=");
                }
            }
        }

        string = new StringBuilder(string.substring(1, string.length()).replaceAll(" ", ""));
        return string.toString();
    }

    public static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.put("pid", "102");
        json.put("gid", "100584");
        json.put("gameKey", "0gha58u1c9FjZkeAsEmYIzTvp");
        json.put("access_token", "659c-S1gV0DwMXdYjPDlSrSLNYOvA8qUoCSvmdFEHvZugKgNX4Z2BCwF18A7W2gRdG7WiWfKsbZgF6YssZHhaozksI9RBn2QQFTXzmAHtbMd4ginEEtwdKmPCM4JbJGg1ollqoNE0PcGENpa4F3e7EdSOa_JFyE6XyUQN1iurJU3F8MZfLlTIcTR9USYoHX15vsAkCht_0mrapZblkeY1_8HFrmK8rlenbZLxccy7PrMz5eZ9uPPDJL5OYiEahyrtLENB8SVmlGofJfQw8wUjN8_XVZSfLMujdwz24");
        String url = "http://192.168.1.156:9020/Faxing/reg?" +
                "&tpyeCode=dimai" +
                "&regParamJson=" + json.toJSONString();
      /*  ExecutorService service= Executors.newCachedThreadPool();
        for (int i = 0; i < 3000; i++) {
            service.submit(new Runnable() {
                @Override
                public void run() {
                    get(url);
                }
            });
        }*/
        com.yutou.bilibili.Tools.Log.i(url);
        //String str=get(url);
    }
}
