package com.ulyssesss.dota.util;

import net.sf.json.JSONObject;
import okhttp3.*;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by jiangyue on 2017/7/15.
 */
public class HttpUtils {

    private static Logger logger = Logger.getLogger(HttpUtils.class);

    private static OkHttpClient client = new OkHttpClient();

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType TEXT = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");

    public static String sendPostRequest(String url, JSONObject object) throws IOException {
        RequestBody body = RequestBody.create(JSON, object.toString());
        Request request = new Request.Builder().url(url).post(body).build();
        return client.newCall(request).execute().body().string();
    }

    public static String sendGetRequest(String url) throws IOException {
        Request request = new Request.Builder().url(url).get().build();
        return client.newCall(request).execute().body().string();
    }

    public static String sendGetRequestWithCookie(String url, String cookie) throws IOException {
        Request request = new Request.Builder().url(url).get().header("Cookie", cookie).build();
        return client.newCall(request).execute().body().string();
    }

    public static String sendJsonPostRequestWithCookie(String url, JSONObject json, String cookie) throws IOException {
        RequestBody body = RequestBody.create(JSON, json.toString());
        Request request = new Request.Builder().url(url).post(body).header("Cookie", cookie).build();
        return client.newCall(request).execute().body().string();
    }

    public static String sendTextPostRequestWithCookie(String url, String body, String cookie) throws IOException {
        RequestBody requestBody = RequestBody.create(TEXT, body);
        Request request = new Request.Builder().url(url).post(requestBody).header("Cookie", cookie).build();
        return client.newCall(request).execute().body().string();
    }

    public static void downloadGet(String url, String path, String fileName) {
        Request request = new Request.Builder().url(url).get().build();
        client.newCall(request).enqueue(downloadCallback(path, fileName));
    }

    public static void downloadPost(String url, String path, String fileName, String cookies, String body) {
        RequestBody requestBody = RequestBody.create(TEXT, body);
        Request request = new Request.Builder().url(url).post(requestBody).header("Cookie", cookies).build();
        client.newCall(request).enqueue(downloadCallback(path, fileName));
    }

    private static Callback downloadCallback(String path, String fileName) {
        return new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                logger.error(ExceptionUtils.getTraceInfo(e));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = response.body().byteStream();
                FileOutputStream fos = new FileOutputStream(new File(path, fileName));
                downloadByStream(is, fos);
            }
        };
    }

    private static void downloadByStream(InputStream is, FileOutputStream fos) {
        try {
            byte[] buf = new byte[2048];
            int len;
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
        } catch (Exception e) {
            logger.error("文件下载失败\n" + ExceptionUtils.getTraceInfo(e));
        } finally {
            closeStream(is, fos);
        }
    }

    private static void closeStream(InputStream is, FileOutputStream fos) {
        try {
            if (is != null) is.close();
            if (fos != null) fos.close();
        } catch (IOException e) {
            logger.error(ExceptionUtils.getTraceInfo(e));
        }
    }
}