package com.sheep.gamegroup.util;


import com.sheep.jiuyan.samllsheep.BuildConfig;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by realicing on 2018/4/17.
 * realicing@sina.com
 */
public class RxjavaCountDownTimer {

    public static RxjavaCountDownTimer getInstance(long count) {
        RxjavaCountDownTimer timer = new RxjavaCountDownTimer();
        timer.init(0,count,0,1, TimeUnit.SECONDS);
        return timer;
    }
    public static RxjavaCountDownTimer getInstance(long start, long count, long initialDelay, long period, TimeUnit unit) {
        RxjavaCountDownTimer timer = new RxjavaCountDownTimer();
        timer.init(start, count, initialDelay, period, unit);
        return timer;
    }
    private Disposable mDisposable;
    private Flowable<Long> flowable;
    private void init(long start, final long count, long initialDelay, long period, TimeUnit unit) {
        flowable = Flowable.intervalRange(start, count+1, initialDelay, period, unit)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong){
                        if(BuildConfig.DEBUG)
                            System.out.println("onTimerAccept aLong = "+aLong);
                        if(count == aLong){
                            if(onTickListener != null)
                                onTickListener.onFinish();
                        } else {
                            if(onTickListener != null)
                                onTickListener.onTicker(count - aLong);
                        }
                    }
                });
    }

    public RxjavaCountDownTimer setOnTickListener(OnTickListener onTickListener) {
        this.onTickListener = onTickListener;
        return this;
    }

    private OnTickListener onTickListener;
    public RxjavaCountDownTimer start() {
        mDisposable = flowable.subscribe();
        return this;
    }
    public void clear() {
        try {
            mDisposable.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public interface OnTickListener{

        void onFinish();

        void onTicker(long time);
    }
}