package cn.yyxx.commsdk.core.network;

import android.content.Context;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import cn.yyxx.commsdk.base.entity.ResultInfo;
import cn.yyxx.commsdk.base.internal.IRequestCallback;
import cn.yyxx.commsdk.base.utils.Logger;
import cn.yyxx.commsdk.core.SdkDrive;
import cn.yyxx.support.JsonUtils;
import cn.yyxx.support.volley.VolleySingleton;
import cn.yyxx.support.volley.source.AuthFailureError;
import cn.yyxx.support.volley.source.DefaultRetryPolicy;
import cn.yyxx.support.volley.source.Request;
import cn.yyxx.support.volley.source.Response;
import cn.yyxx.support.volley.source.VolleyError;
import cn.yyxx.support.volley.source.toolbox.StringRequest;

/**
 * @author #Suyghur.
 * Created on 2021/04/28
 */
public class VolleyRequest {

    /**
     * 超时时间
     */
    private static final int MAX_TIMEOUT = 10 * 1000;


    public static void post(Context context, String url,String params, final IRequestCallback callback) {
        try {

            Logger.logHandler("请求地址 : " + url + "\n");
            Logger.logHandler("请求参数 : " + params.toString() + "\n");
            Logger.d("请求地址 : " + url);
            Logger.d("请求参数 : " + params.toString());

            StringRequest request = new StringRequest(Request.Method.POST,Hosts.HOST, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {


                    String deData =  SdkDrive.getInstance().parseJob(s);

                    ResultInfo resultInfo = new ResultInfo();
                    JSONObject json = null;
                    try {
                         json = new JSONObject(deData);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (json != null) {
                        try {
                            resultInfo.code = json.getInt("code");
                            resultInfo.msg = json.getString("msg");
                            if (JsonUtils.hasJsonKey(json, "data")) {
                                resultInfo.data = json.getString("data");
                            } else {
                                resultInfo.data = "";
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            resultInfo.code = -1;
                            resultInfo.msg = "数据解析异常";
                            resultInfo.data = "";
                        }
                    } else {
                        resultInfo.code = -1;
                        resultInfo.msg = "接口请求异常";
                        resultInfo.data = "";
                    }
                    Logger.logHandler("返回内容 : " + resultInfo.toString());
                    Logger.d("onResponse : " + resultInfo.toString());
                    if (callback != null) {
                        callback.onResponse(resultInfo);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Logger.d(volleyError.toString());
                    if (callback != null) {
                        callback.onResponse(getErrorResultInfo(volleyError));
                    }
                }
            })
            {
                @Override
                public Map<String, String> getHeaders() {
                    HashMap<String, String> headers = new HashMap<>();
                    headers.put("Accept", "text/plain");
                    headers.put("Content-Type", "text/plain;charset=UTF-8");
                    return headers;
                }


                @Override
                public byte[] getBody() throws AuthFailureError {
                    byte[] bd= new byte[0];
                    try {
                        bd = params.getBytes(getParamsEncoding());
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    return bd;
                }
            };

            request.setRetryPolicy(new DefaultRetryPolicy(MAX_TIMEOUT, 1, 1.0f));
            VolleySingleton.getInstance(context.getApplicationContext()).addToRequestQueue(context.getApplicationContext(), request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static ResultInfo getErrorResultInfo(VolleyError volleyError) {
        ResultInfo resultInfo = new ResultInfo();
        if (volleyError.networkResponse != null) {
            resultInfo.code = volleyError.networkResponse.statusCode;
            resultInfo.msg = volleyError.getMessage();
        } else {
            resultInfo.code = 400;
            resultInfo.msg = "网络异常";
        }
        resultInfo.data = "";
        return resultInfo;
    }
}
