package cn.dankal.basiclib.base.lifecycle;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import cn.dankal.basiclib.util.Logger;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

public class MyLifeCycleObserver implements LifecycleObserver {


    private ObservableEmitter emitter;

    private Observable observable;

    public MyLifeCycleObserver() {

        observable = Observable.create(new ObservableOnSubscribe<Lifecycle.Event>() {
            @Override
            public void subscribe(ObservableEmitter<Lifecycle.Event> nxt) throws Exception {
                emitter = nxt;
            }
        });

//        Observer observer=new Observer() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(Object o) {
//
//            }
//
//            @Override
//            public void onError(Throwable e) {
//
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        };
//
//        observable.subscribe(observer);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate() {
        Logger.e("onCreate");
        if (emitter != null) {
            emitter.onNext(Lifecycle.Event.ON_CREATE);
        }

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onStart() {
        Logger.e("onStart");
        if (emitter != null) {
            emitter.onNext(Lifecycle.Event.ON_CREATE);
        }
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        Logger.e("onResume");
        if (emitter != null) {
            emitter.onNext(Lifecycle.Event.ON_RESUME);
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        Logger.e("onPause");
        if (emitter != null) {
            emitter.onNext(Lifecycle.Event.ON_PAUSE);
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        Logger.e("onStop");
        if (emitter != null) {
            emitter.onNext(Lifecycle.Event.ON_STOP);
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        Logger.e("onDestroy");
        if (emitter != null) {
            emitter.onNext(Lifecycle.Event.ON_DESTROY);
        }
    }


    public Observable getObservable() {
        return observable;
    }
}
