
package com.ydl.ydlcommon.base.delegate

import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import com.trello.rxlifecycle2.android.ActivityEvent
import com.ydl.ydlcommon.base.lifecycle.IActivityLifecycleable
import io.reactivex.subjects.Subject

/**
 * Created by haorui on 2019-08-22 .
 * Des: Activity 生命周期代理类
 *      使所有继承IActivityLifecycleable的实现类，支持RxLifecycle特性
 */
class ActivityDelegate : Application.ActivityLifecycleCallbacks {

    private val mFragmentLifecycle = FragmentDelegate()

    /**
     * 通过桥梁对象 `BehaviorSubject<ActivityEvent> mLifecycleSubject`
     * 在每个 Activity 的生命周期中发出对应的生命周期事件
     */
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        if (activity is IActivityLifecycleable) {
            obtainSubject(activity).onNext(ActivityEvent.CREATE)
            if (activity is FragmentActivity) {
                (activity as FragmentActivity).supportFragmentManager.registerFragmentLifecycleCallbacks(
                    mFragmentLifecycle,
                    true
                )
            }
        }
    }

    override fun onActivityStarted(activity: Activity) {
        if (activity is IActivityLifecycleable) {
            obtainSubject(activity).onNext(ActivityEvent.START)
        }
    }

    override fun onActivityResumed(activity: Activity) {
        if (activity is IActivityLifecycleable) {
            obtainSubject(activity).onNext(ActivityEvent.RESUME)
        }
    }

    override fun onActivityPaused(activity: Activity) {
        if (activity is IActivityLifecycleable) {
            obtainSubject(activity).onNext(ActivityEvent.PAUSE)
        }
    }

    override fun onActivityStopped(activity: Activity) {
        if (activity is IActivityLifecycleable) {
            obtainSubject(activity).onNext(ActivityEvent.STOP)
        }
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        if (activity is IActivityLifecycleable) {
            obtainSubject(activity).onNext(ActivityEvent.DESTROY)
        }
    }

    private fun obtainSubject(activity: Activity): Subject<ActivityEvent> {
        return (activity as IActivityLifecycleable).provideLifecycleSubject()
    }
}
