package com.easy.clean.business.helper;

import android.text.TextUtils;

import com.easy.clean.utils.LogEx;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class ReportUtils {
    private static String TAG = "ReportUtils";

    public static String doPost(String urlPath, Map<String, String> paramsMap, String json) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(urlPath).openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setConnectTimeout(5000);
            if (!TextUtils.isEmpty(json)) {
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Content-Length", Integer.toString(json.getBytes().length));

                conn.getOutputStream().write(json.getBytes());
            }

            StringBuilder result = new StringBuilder();
            for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                result.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
            if (result.length() > 0) {
                try {
                    conn.getOutputStream().write(result.substring(1).getBytes());
                } catch (Exception e) {
                }
            } else {
                // conn.getOutputStream().write(result.substring(0).getBytes());
            }

            if (conn.getResponseCode() == 200) {
                String s = new BufferedReader(new InputStreamReader(conn.getInputStream())).readLine();
                if (!TextUtils.isEmpty(s)) {
                } else {
                    s = "";
                }
                LogEx.INSTANCE.logDebug(TAG, "code=200", false);
                return s;
            } else {
                LogEx.INSTANCE.logDebug(TAG, "code!=200", false);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{ \"success\": false,\n   \"errorMsg\": \"后台服务器开小差了!\",\n     \"result\":{}}";
    }
}
