package com.yidianling.ydlcommon.core.base

import android.app.Activity
import android.content.res.Resources
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v7.app.AppCompatActivity
import android.util.Log
import com.trello.rxlifecycle2.android.ActivityEvent
import com.yidianling.ydlcommon.core.base.lifecycle.IActivityLifecycleable
import com.yidianling.ydlcommon.core.bean.StatusBarOptions
import com.yidianling.ydlcommon.core.utils.ActivityManager
import com.yidianling.ydlcommon.core.utils.AndroidSystemHelper
import com.yidianling.ydlcommon.core.utils.StatusBarUtils
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import kotlin.properties.Delegates

/**
 * 基础 Activity，所有的 Activity 都继承此类
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/01/27
 */
abstract class BaseActivity : AppCompatActivity(),IActivityLifecycleable {

    private val mLifecycleSubject = BehaviorSubject.create<ActivityEvent>()
    var mContext: Activity by Delegates.notNull()
    var statusBarOption: StatusBarOptions? = null

    override fun provideLifecycleSubject(): Subject<ActivityEvent> {
        return mLifecycleSubject;
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        //修复Android 8.0 崩溃
        AndroidSystemHelper.fixAndroidOrientationBug(this)
        super.onCreate(savedInstanceState)

        Log.d("TAG", javaClass.name)
        mContext = this

        val layoutResId = layoutResId()
        if (layoutResId != 0) setContentView(layoutResId())
        ActivityManager.getInstance().addStack(this)
        initDataAndEvent()
    }

    override fun setRequestedOrientation(requestedOrientation: Int) {
        if (AndroidSystemHelper.isAllowSetOrientation(this)) {
            super.setRequestedOrientation(requestedOrientation)
        }
    }

    override fun setContentView(@LayoutRes layoutResID: Int) {
        if (statusBarOption!=null && statusBarOption?.isAddStatusView!!) {
            super.setContentView(StatusBarUtils.initStatusBarView(this,layoutResID,statusBarOption!!))
            AndroidSystemHelper.fixAndroidBug5497Workaround(this)
        } else {
            super.setContentView(layoutResID)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityManager.getInstance().removeStack(this)
        AndroidSystemHelper.fixInputMethodManagerLeak(this)
    }

    @LayoutRes
    protected abstract fun layoutResId(): Int

    // 初始化数据和事件
    protected abstract fun initDataAndEvent()

    override fun getResources(): Resources {
        //解决 修改系统字体大小后 H5页面大小比例不正常现象
        val res = super.getResources()
        return AndroidSystemHelper.fixResourcesScale(res)
    }

    open fun initStatusViewOptions(isAddStatusView:Boolean,statusBarDarkMode:Boolean,statusColor:String){
        statusBarOption = StatusBarOptions(isAddStatusView,statusBarDarkMode,statusColor)
    }
}