package com.joe.print.mvp.print.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.jess.arms.integration.RepositoryManager;
import com.joe.print.mvp.model.server.GetPrintInfoService;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

/**
 * 在用戶登錄成功後，打開打印service，每隔3~5秒請求一次。請求到了數據就進行打印邏輯
 */
public class PrjService extends Service {

    private final String TAG = "PrjService";
    @Inject
    RxErrorHandler mErrorHandler;
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("eee", "打開打印服務");
        //開始請求
        Observable.interval(0,3, TimeUnit.SECONDS)
                .doOnNext(aLong ->{
                    Log.d(TAG, "第" + aLong + "次輪詢");
                    /*
                     * 步骤3：通过Retrofit发送网络请求
                     *
                     **/
                    new RepositoryManager().obtainRetrofitService(GetPrintInfoService.class)
                            .getPrintInfo("26")
                            .subscribeOn(Schedulers.io())
                            .doOnSubscribe(disposable -> {})
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doAfterTerminate(() -> {})
                            .subscribe(new ErrorHandleSubscriber<Object>(mErrorHandler) {
                                @Override
                                public void onNext(Object o) {
                                    Log.e("eee", "请求到：" + o);
                                }

                                @Override
                                public void onError(Throwable t) {
                                    super.onError(t);
                                    t.printStackTrace();
                                }
                            });
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long aLong) {

            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "对Error事件作出响应" + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "对onComplete事件作出响应");
            }
        });
    }



    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }
}
