package com.hc.request.core;

import android.support.annotation.NonNull;

import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.RequestQueue;
import com.yanzhenjie.nohttp.rest.Response;

/**
 * 请求队列单例
 *
 * @author Jewel
 * @version 1.0
 * @since 2018/04/02
 */

public class CallServer {

    private RequestQueue queue;

    public void requestString(int what, final Request<String> request, @NonNull final IHttpCallback<String> callback) {
        queue.add(what, request, new OnResponseListener<String>() {

            @Override
            public void onStart(int what) {
                callback.onStart(what);
            }

            @Override
            public void onSucceed(int what, Response<String> response) {
                callback.onSuccess(what, response.get());
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                callback.onError(what, response.getException());
            }

            @Override
            public void onFinish(int what) {
                callback.onFinish(what);
            }
        });
    }

    public <T> void request(int what, final Request<T> request, @NonNull final IHttpCallback<T> callback) {
        queue.add(what, request, new OnResponseListener<T>() {
            @Override
            public void onStart(int what) {
                callback.onStart(what);
            }

            @Override
            public void onSucceed(int what, Response<T> response) {
                if (response == null) {
                    callback.onFail(what, "返回数据为空");
                    return;
                }
                T result = response.get();
                if (result == null) {
                    callback.onFail(what, "返回数据为空");
                    return;
                }
                callback.onSuccess(what, result);
            }

            @Override
            public void onFailed(int what, Response<T> response) {
                callback.onError(what, response.getException());
            }

            @Override
            public void onFinish(int what) {
                callback.onFinish(what);
            }
        });
    }

    public void stop() {
        queue.stop();
    }

    private static CallServer instance;

    public static CallServer getInstance() {
        if (instance == null) {
            synchronized (CallServer.class) {
                if (instance == null) {
                    instance = new CallServer();
                }
            }
        }
        return instance;
    }

    private CallServer() {
        queue = NoHttp.newRequestQueue(3);
    }
}
