package com.tofly.ghrq_route.module.gps.service;

import android.content.Context;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.url.NetRequestURL.newApi_dyrq;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.base.URLResponseCode.ErrorCode;
import com.tofly.ghrq_route.module.gps.controller.GPSCallBack;
import com.tofly.ghrq_route.module.gps.domain.GPSDataBean;
import com.tofly.ghrq_route.common.util.net.volley.JsonRequestConstant;

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

/**
 * Created by Amu on 2017/3/15.
 */

public class GPSServiceImpl implements IGPSService {

    private Context mContext;

    public GPSServiceImpl(Context context){
        mContext = context;
    }

    @Override
    public void uploadGpsInfo(Context context, final GPSDataBean gpsData, final GPSCallBack gpsCallBack) {
        //上传GPS信息
        String url = newApi_dyrq.getGpsAddUrl();
        StringRequest postRequest = new StringRequest(Request.Method.POST,
                url, response -> {
                    URLResponseCode.URLResponse urlResponse = new URLResponseCode.URLResponse(response);
                    if (urlResponse.getCode() == ErrorCode.SUCCESS){
                        gpsCallBack.onUploadGpsInfo(true, urlResponse.getCode(), urlResponse.getMessage());
                    }else {
                        gpsCallBack.onUploadGpsInfo(
                                false, urlResponse.getCode(), urlResponse.getMessage());
                    }
                }, error -> {
                    //登录失败
                    if (error.networkResponse != null) {
                        try {
                            String errString = new String(error.networkResponse.data, "UTF-8");
                            gpsCallBack.onUploadGpsInfo(
                                    false, error.networkResponse.statusCode, errString);
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            gpsCallBack.onUploadGpsInfo(
                                    false, error.networkResponse.statusCode, null);
                        }
                    }else {
                        String errString = ErrorCode.getErrorMessage(ErrorCode.HTTPCONN_TIMEOUT);
                        gpsCallBack.onUploadGpsInfo(
                                false, ErrorCode.HTTPCONN_TIMEOUT, errString);
                    }
                }){
            @Override
            public byte[] getBody()  {
                Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                String pdaDevice = gson.toJson(gpsData);
                return pdaDevice.getBytes();
            }

            @Override
            public String getBodyContentType() {
                return JsonRequestConstant.PROTOCOL_CONTENT_TYPE;
            }

            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(context.getClass().getName(), postRequest);
    }

    @Override
    public void uploadBatchGpsInfo(Context context, final List<GPSDataBean> gpsDataList, final GPSCallBack gpsCallBack) {
        //上传GPS信息
        String url = newApi_dyrq.getGpsAddBatchUrl();
        StringRequest postRequest = new StringRequest(Request.Method.POST,
                url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                URLResponseCode.URLResponse urlResponse = new URLResponseCode.URLResponse(response);
                if (urlResponse.getCode() == ErrorCode.SUCCESS){
                    gpsCallBack.onUploadBatchGpsInfo(true, urlResponse.getCode(), urlResponse.getMessage(), null);
                }else {
                    List<GPSDataBean> gpsDataList = null;
                    if (urlResponse.getCode() == ErrorCode.UNKNOWN_ERROR){
                        String rowsArray = urlResponse.getResult();
                        int resCode = -1;
                        boolean result = false;
                        String parseErrMsg = "用户解析失败";
                        if (rowsArray != null){
                            try {
                                Gson gson = new Gson();
                                List<GPSDataBean> gpsDatas = gson.fromJson(rowsArray, new TypeToken<List<GPSDataBean>>(){}.getType());
                                if (gpsDatas != null && gpsDatas.size() >= 0){
                                    gpsDataList = gpsDatas;
                                    resCode = urlResponse.getCode();
                                    parseErrMsg = urlResponse.getMessage();
                                }
                            }catch (Exception e){
                                gpsCallBack.onUploadBatchGpsInfo(false, resCode, parseErrMsg, null);
                            }
                        }
                    }
                    gpsCallBack.onUploadBatchGpsInfo(false, urlResponse.getCode(),
                            urlResponse.getMessage(), gpsDataList);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //登录失败
                if (error.networkResponse != null) {
                    try {
                        String errString = new String(error.networkResponse.data, "UTF-8");
                        gpsCallBack.onUploadBatchGpsInfo(
                                false, error.networkResponse.statusCode, errString, null);
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        gpsCallBack.onUploadBatchGpsInfo(
                                false, error.networkResponse.statusCode, null, null);
                    }
                }else {
                    String errString = ErrorCode.getErrorMessage(ErrorCode.HTTPCONN_TIMEOUT);
                    gpsCallBack.onUploadBatchGpsInfo(
                            false, ErrorCode.HTTPCONN_TIMEOUT, errString, null);
                }
            }
        }){
            @Override
            public byte[] getBody() {
                Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                String json = gson.toJson(gpsDataList);
                return json.getBytes();
            }

            @Override
            public String getBodyContentType() {
                return JsonRequestConstant.PROTOCOL_CONTENT_TYPE;
            }

            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(mContext.getClass().getName(), postRequest, BaseApp.UPLOAD_BATCH_TIMEOUT_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    }

    @Override
    public void updateGpsStatus(Context context, final GPSDataBean gpsData, final GPSCallBack gpsCallBack) {
        //上传GPS信息
        String url = newApi_dyrq.getUpdateGpsStatusUrl();
        StringRequest postRequest = new StringRequest(Request.Method.POST,
                url, response -> {
            URLResponseCode.URLResponse urlResponse = new URLResponseCode.URLResponse(response);
            if (urlResponse.getCode() == ErrorCode.SUCCESS){
                gpsCallBack.onUploadGpsInfo(true, urlResponse.getCode(), urlResponse.getMessage());
            }else {
                gpsCallBack.onUploadGpsInfo(
                        false, urlResponse.getCode(), urlResponse.getMessage());
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                try {
                    String errString = new String(error.networkResponse.data, "UTF-8");
                    gpsCallBack.onUploadGpsInfo(
                            false, error.networkResponse.statusCode, errString);
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    gpsCallBack.onUploadGpsInfo(
                            false, error.networkResponse.statusCode, null);
                }
            }else {
                String errString = ErrorCode.getErrorMessage(ErrorCode.HTTPCONN_TIMEOUT);
                gpsCallBack.onUploadGpsInfo(
                        false, ErrorCode.HTTPCONN_TIMEOUT, errString);
            }
        }){

            @Override
            public byte[] getBody()  {
                JsonObject root = new JsonObject();
                root.addProperty("x", gpsData.getLng());
                root.addProperty("y", gpsData.getLat());
                String gpsAddr = gpsData.getAddress();
                if (gpsAddr != null && !gpsAddr.isEmpty()){
                    root.addProperty(("location"), gpsAddr);
                }
                root.addProperty(("locationType"), gpsData.getNetwork()+"");
                root.addProperty("gpstime", gpsData.getGpstime());
                root.addProperty("radius", gpsData.getGps_precision());
                root.addProperty("gps_star", gpsData.getGps_star() + "");
                root.addProperty("speed", gpsData.getSpeed());
                root.addProperty("distance", gpsData.getDistance() + "");
                root.addProperty("systemtime", gpsData.getCheck_time());
                root.addProperty("state", gpsData.getState() + "");
                Gson gson = new Gson();
                String gpsStatus = gson.toJson(root);
                return gpsStatus.getBytes();
            }

            @Override
            public String getBodyContentType() {
                return JsonRequestConstant.PROTOCOL_CONTENT_TYPE;
            }

            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(context.getClass().getName(), postRequest);
    }
}
