package com.zhaohaoting.framework.mvchelper.okhttp.okhttp;

import android.text.TextUtils;
import android.util.Log;

import com.zhaohaoting.framework.mvchelper.mvc.ResponseSender;
import com.zhaohaoting.framework.mvchelper.okhttp.exception.RequestException;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * author：Created by ZHT on 2017/11/2 9:23
 * email：526309416@qq.com
 * desc：请求处理类 若需要自己解析 解开注释
 * 不满足需求 抽象类可扩展方法
 */
public abstract class CallBackParser<DATA,RESULT_DATA> implements Callback, ResponseParser<RESULT_DATA> {

    protected static final int FAILURE = 1;//失败
    protected static final int LOCAL_FAILURE = -1000;//本地错误

    protected ResponseParser<RESULT_DATA> responseParser; //自定义解析
    protected ResponseSender<DATA> sender;


    public void setSender(ResponseSender<DATA> sender) {
        this.sender = sender;
    }

    /**
     * 自定义解析器
     */
    public void setResponseParser(ResponseParser<RESULT_DATA> responseParser) {
        this.responseParser = responseParser;
    }

    @Override
    public void onFailure(Call call, IOException e) {
        String tipMsg;//错误提示
        if (e instanceof SocketTimeoutException) {
            tipMsg = "链接超时";
        } else if (e instanceof ConnectException) {
            if (e.getMessage().contains("Network is unreachable"))
                tipMsg = "无网络";
            else if (e.getMessage().contains("failed to connect to")) {
                tipMsg = "链接服务器失败";
            } else {
                tipMsg = "网络不给力啊";
            }
        } else {
            tipMsg = "网络不给力啊";
        }
        sender.sendError(new RequestException(TextUtils.isEmpty(tipMsg) ? "" : tipMsg).setCode(FAILURE));
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            String resultString = response.body().string();
            Log.e("服务器返回 " + Thread.currentThread().getName(), response.request().url().url().getPath() + "  Token:" + response.request().header("accessToken") + "\n" + resultString);
            try {
                parseResult(resultString);
            } catch (Exception e) {
                e.printStackTrace();
                sender.sendError(new RequestException("数据解析错误").setCode(LOCAL_FAILURE));
            }
        } else {
            sender.sendError(new RequestException(TextUtils.isEmpty(response.message()) ? "" : response.message()).setCode(response.code()));
        }
    }

    public abstract void parseResult(String resultString);

}