package com.zhimai.websocket.http;

import android.os.Looper;

import java.io.IOException;

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

public class CallbackToMainThread implements Callback {
    private MCallback mCallback = null;
    private Call mCall = null;
    private IOException mIOException = null;
    private Response mStringResponse = null;

    /**
     * @param callback 这里是请求结果的回调，其回调方法将会在UI线程内执行
     */
    public CallbackToMainThread(MCallback callback) {
        mCallback = callback;
    }

    /**
     * 此处new android.os.Handler(Looper.getMainLooper()).post(runnableFailureUI)是将失败通过UI线程返回
     */
    @Override
    public void onFailure(Call call, IOException e) {
        mCall = call;
        mIOException = e;
        new android.os.Handler(Looper.getMainLooper()).post(runnableFailureUI);
    }

    /**
     * 这里会根据主线程内Callback的getTClassName实现来获取想要得到的数据类型，然后去做类型转化
     */
    @Override
    public void onResponse(Call call, Response response) {
        mCall = call;
        mStringResponse = response;
        new android.os.Handler(Looper.getMainLooper()).post(runnableSuccessUI);

    }

    Runnable runnableFailureUI = new Runnable() {
        @Override
        public void run() {
            mCallback.onFailure(mCall, mIOException);
        }
    };

    Runnable runnableSuccessUI = new Runnable() {
        @Override
        public void run() {
            try {
                if (mStringResponse != null) {
                    mCallback.onResponse(mCall, mStringResponse);
                }
            } catch (IOException e) {
                mCallback.onFailure(mCall, e);
            }
        }
    };

    /**
     * 此处接口将会在UI线程内实现
     * 成功失败都将会通过这里面的方法返回给UI线程
     */
    public interface MCallback {
        void onFailure(Call call, IOException e);

        void onResponse(Call call, Response response) throws IOException;
    }
}
