package com.zhaohaoting.framework.requset;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.zhaohaoting.framework.abs.entity.ResultEntity;
import com.zhaohaoting.framework.mvchelper.okhttp.exception.RequestException;
import com.zhaohaoting.framework.mvchelper.okhttp.okhttp.CallBackParser;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Response;


/**
 * author：Created by ZHT on 2017/11/29 10:23
 * email：526309416@qq.com
 * desc：请求回调 此类必须抽象 否者则必须调用setResponseParser自定义解析
 */
public abstract class ResultCallback<DATA, RESULT_DATA extends ResultEntity<DATA>> extends CallBackParser<DATA,RESULT_DATA> {

    public static final int NEED_LOGIN = 6666;//需要从新登录
    public static final int REQUEST_SUCCESS = 0;//请求成功

    public ResultCallback() {
    }

    public ResultCallback(RequestCallback<DATA> requestCallback) {
        this.requestCallback = requestCallback;
    }


    @Override
    public void parseResult(String resultString) {
        Type type = (((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]);
        RESULT_DATA resultEntity = new Gson().fromJson(resultString, type);
        int code = resultEntity.getError();
        if (code == REQUEST_SUCCESS) {
            sender.sendData(resultEntity.getData());
            if (requestCallback != null) {
                requestCallback.requestSuccess(resultEntity.getData());
            }
        } else {
            if (code == NEED_LOGIN) {
//                MyApplication.getUser().deleteUser();
//                JPushInterface.stopPush(MyApplication.getContext());
            }
            sender.sendError(new RequestException(TextUtils.isEmpty(resultEntity.getMessage()) ? "" : resultEntity.getMessage()).setCode(code)); //请求成功 用于弹出提示｛msg:"";data:null;code:11｝
        }
    }

    @Override
    public RESULT_DATA parse(Response response) throws Exception {
        return responseParser.parse(response);
    }

    private RequestCallback<DATA> requestCallback;

    public interface RequestCallback<DATA> {
        void requestSuccess(DATA dataSource);
    }

    public void setRequestCallback(RequestCallback<DATA> requestCallback) {
        this.requestCallback = requestCallback;
    }
}
