package com.tofly.ghrq_route.module.deviceInfo.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.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.base.url.NetRequestURL.newApi_dyrq;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.module.deviceInfo.controller.DeviceInfoCallback;
import com.tofly.ghrq_route.module.deviceInfo.domain.DeviceInfoBean;
import com.tofly.ghrq_route.common.util.net.volley.JsonRequestConstant;

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

/**
 * Created by Amu on 2017/4/24.
 */

public class DeviceInfoServiceImpl implements IDeviceInfoService {

    private Context mContext;

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

    @Override
    public void uploadDevcieInfo(final String token, final String userid, final DeviceInfoBean deviceInfo, final int workState, final DeviceInfoCallback deviceInfoCallback) {
        String url = newApi_dyrq.getUploadDeviceInfoUrl();
        final StringRequest postRequest = new StringRequest(Request.Method.POST,
                url, response -> {
                    URLResponseCode.URLResponse urlResponse = new URLResponseCode.URLResponse(response);
                    if (urlResponse.getCode() == URLResponseCode.ErrorCode.SUCCESS){
                        int section = 0;
                        String strSection = urlResponse.queryResult("section");
                        if (strSection != null && !strSection.isEmpty()){
                            section = Integer.parseInt(strSection);
                        }
                        deviceInfoCallback.onUploadDeviceInfo(true, urlResponse.getCode(), urlResponse.getMessage(), section);
                    }else {
                        deviceInfoCallback.onUploadDeviceInfo(
                                false, urlResponse.getCode(), urlResponse.getMessage(), 0);
                    }
                }, error -> {
                    //登录失败
                    if (error.networkResponse != null) {
                        try {
                            String errString = new String(error.networkResponse.data, "UTF-8");
                            deviceInfoCallback.onUploadDeviceInfo(
                                    false, error.networkResponse.statusCode, errString, 0);
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            deviceInfoCallback.onUploadDeviceInfo(
                                    false, error.networkResponse.statusCode, null, 0);
                        }
                    }else {
                        String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                        deviceInfoCallback.onUploadDeviceInfo(
                                false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, 0);
                    }
                }){
            /*@Override
            protected Map<String, String> getParams(){
                //参数拼装:表单提交方式
                Map<String, String> params = new HashMap<String, String>();
                int gps_state = deviceInfo.getGps_state();
                params.put("gps_state",  gps_state + "");
                if (gps_state == 1){
                    //定位精度 gps状态为1该项必填，gps状态为0时此项可填
                    params.put("gps_precision", deviceInfo.getGps_precision());
                    //卫星颗数 gps状态为1该项必填，gps状态为0时此项可填
                    params.put("gps_star", deviceInfo.getGps_star() + "");
                }
                params.put("network_type", deviceInfo.getNetwork_type() + "");
                params.put("network_state", deviceInfo.getNetwork_state() + "");
                params.put("electricity", deviceInfo.getElectricity() + "");
                params.put("check_time", deviceInfo.getCheck_time());
                String gpsNotes = deviceInfo.getNote();
                if (gpsNotes != null && !gpsNotes.isEmpty()){
                    params.put(("note"), gpsNotes);
                }
                String freeSpace = deviceInfo.getResidual_space();
                if (freeSpace != null && !freeSpace.isEmpty()){
                    *//*手机剩余空间MB*//*
                    params.put("residual_space", freeSpace);
                }
                int carMode = deviceInfo.getGps_type();
                params.put("gps_type", carMode + "");
                params.put("work_state", workState + "");
                String carid = deviceInfo.getCarid();
                if (carid != null && !carid.isEmpty())
                    params.put("carid", carid);
                return params;
            }*/

            @Override
            public byte[] getBody()  {
                Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                String pdaDevice = gson.toJson(deviceInfo);
                return pdaDevice.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);
    }

    @Override
    public void uploadBatchDeviceInfo(final String token, final String userid, final List<DeviceInfoBean> deviceInfoList, final DeviceInfoCallback deviceInfoCallback) {
        String url = NetRequestURL.getUploadBatchDeviceInfoUrl();
        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() == URLResponseCode.ErrorCode.SUCCESS){
                    deviceInfoCallback.onUploadBatchDeviceInfo(true, urlResponse.getCode(), urlResponse.getMessage());
                }else {
                    deviceInfoCallback.onUploadBatchDeviceInfo(
                            false, urlResponse.getCode(), urlResponse.getMessage());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //登录失败
                if (error.networkResponse != null) {
                    try {
                        String errString = new String(error.networkResponse.data, "UTF-8");
                        deviceInfoCallback.onUploadBatchDeviceInfo(
                                false, error.networkResponse.statusCode, errString);
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        deviceInfoCallback.onUploadBatchDeviceInfo(
                                false, error.networkResponse.statusCode, null);
                    }
                }else {
                    String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                    deviceInfoCallback.onUploadBatchDeviceInfo(
                            false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString);
                }
            }
        }){
            @Override
            public byte[] getBody(){
                Gson gson = new Gson();
                String json = gson.toJson(deviceInfoList);
                return json.getBytes();
            }

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

            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                Map<String, String> params = new HashMap<String, String>();
                params.put("token", token);
                params.put("userid", userid);
                return params;
            }
        };
        BaseApp.addRequest(mContext.getClass().getName(), postRequest, BaseApp.UPLOAD_BATCH_TIMEOUT_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    }
}
