package com.itant.shiwushu.net;

import android.os.Handler;
import android.support.annotation.NonNull;

import com.itant.shiwushu.LAFApplication;

import java.io.IOException;

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

/**
 * 转到主线程
 * Created by Jason on 2018/9/1.
 */

public abstract class ElasticCallback implements Callback {
    private Handler mainHandler = new Handler(LAFApplication.instance.getMainLooper());
    @Override
    public void onFailure(@NonNull final Call call, @NonNull final IOException e) {
        mainHandler.post(new Runnable() {

            @Override
            public void run() {
                onRequestComplete();
                onRequestFailure(call, e);
            }
        });
    }

    @Override
    public void onResponse(@NonNull final Call call, @NonNull final Response response) throws IOException {

        ResponseBody body = response.body();
        if (body != null) {
            final String result = body.string();
            final int code = response.code();

            mainHandler.post(new Runnable() {

                @Override
                public void run() {
                    onRequestComplete();
                    try {
                        onRequestResponse(code, result);
                    } catch (IOException e) {
                        e.printStackTrace();
                        onRequestFailure(call, e);
                    }
                }
            });
        } else {
            onRequestFailure(call, new IOException("body is empty"));
        }

    }

    public abstract void onRequestFailure(Call call, IOException e);
    public abstract void onRequestResponse(int code, String result) throws IOException;
    //public abstract void onRequestResponse(Call call, Response response) throws IOException;
    public abstract void onRequestComplete();
}
