package com.duben.microtribe.manager;

import com.duben.microtribe.MintsApplication;
import com.duben.library.net.neterror.HttpResponseFunc;
import com.duben.microtribe.mvp.model.BaseResponse;

import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;

/**
 * 描述：AppHttpManager
 * 作者：孟崔广
 * 时间：2018/01/15 10:51
 * 邮箱：mengcuiguang@cashbang.cn
 */
public class AppHttpManager {

    private static AppHttpManager _inst;

    private MintsApplication application;

    private Observable.Transformer exceptTransformer = null;

    public synchronized static AppHttpManager getInstance(MintsApplication application) {
        if (_inst != null) {
            return _inst;
        } else {
            _inst = new AppHttpManager(application);
            return _inst;
        }
    }

    private AppHttpManager(MintsApplication application) {
        this.application = application;
        return;
    }


    /**
     * @param subscriber
     */
    public Subscription call(Observable observable, Subscriber subscriber) {

        return observable.compose(schedulersTransformer)
                .compose(handleErrTransformer())
                .subscribe(subscriber);
    }

    final Observable.Transformer schedulersTransformer = new Observable.Transformer() {
        @Override
        public Object call(Object observable) {
            Scheduler scheduler = application.defaultSubscribeScheduler();
            return ((Observable) observable).subscribeOn(scheduler)
                    .unsubscribeOn(scheduler)
                    .observeOn(AndroidSchedulers.mainThread());
        }
    };


    /**
     * @param <T>
     * @return
     */
    public <T> Observable.Transformer<BaseResponse<T>, T> handleErrTransformer() {

        if (exceptTransformer != null) {
            return exceptTransformer;
        } else {
            return exceptTransformer = new Observable.Transformer() {
                @Override
                public Object call(Object observable) {
                    return ((Observable) observable)/*.map(new HandleFuc<T>())*/.onErrorResumeNext(new HttpResponseFunc<T>());
                }
            };
        }
    }


}
