package com.yidianling.ydlcommon.custom.base

import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Color
import android.os.Build
import android.support.annotation.LayoutRes
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.yidianling.ydlcommon.R
import com.yidianling.ydlcommon.custom.tool.AndroidBug5497Workaround
import com.yidianling.ydlcommon.custom.tool.StatusBarUtils

/**
 * 简单的基础 Activity，只提供通用基础功能
 */
abstract class SimplyBaseActivity : AppCompatActivity() {

    override fun setContentView(@LayoutRes layoutResID: Int) {
        if (isAddStatusView()){
            val containerView = View.inflate(this, R.layout.layout_root, null) as ViewGroup
            val rootView = containerView.findViewById<LinearLayout>(R.id.ll_root);
            initStatus(rootView);
            val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            val child = View.inflate(this, layoutResID, null)
            rootView.addView(child, params)
            super.setContentView(containerView)
            com.yidianling.ydlcommon.custom.tool.AndroidBug5497Workaround.assistActivity(this);
        }else{
            super.setContentView(layoutResID)
        }
    }

    /**
     * 初始化状态栏
     */
    private fun initStatus(rootView:View) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            val statusView = rootView.findViewById<View>(R.id.view_status_place_holder)
            statusView.setBackgroundColor(Color.parseColor(getStatusColor()))
            val statusBarHeight = StatusBarUtils.getStatusBarHeight(this)
            val layoutParams = statusView.getLayoutParams() as LinearLayout.LayoutParams
            layoutParams.height = statusBarHeight
            statusView.layoutParams = layoutParams
            StatusBarUtils.setTransparentForImageView(this, null)
        }
        if (statusBarDarkMode()){
            StatusBarUtils.statusBarLightMode(this)
        }
    }

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

    open fun isAddStatusView(): Boolean{
        return false
    }

    open fun statusBarDarkMode(): Boolean{
        return false
    }

    open fun getStatusColor(): String{
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return "#FFFFFF"
        }
        return "#1da1f2"
    }
}