package com.ez.ertc.base

import android.util.DisplayMetrics
import android.view.View
import android.view.ViewConfiguration
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.ez.baselib.utils.LogUtil
import com.ez.ertc.R

open class BaseActivity :  AppCompatActivity() {

    protected fun getStatusBarHeight(): Int {
        // status bar height
        var statusBarHeight = 0
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            statusBarHeight = resources.getDimensionPixelSize(resourceId)
        }
        if (statusBarHeight == 0) {
            LogUtil.e(localClassName, "Can not get height of status bar")
        }
        return statusBarHeight
    }

    protected fun getActionBarHeight(): Int {
        // action bar height
        var actionBarHeight = 0
        val styledAttributes = this.theme.obtainStyledAttributes(intArrayOf(R.attr.actionBarSize))
        actionBarHeight = styledAttributes.getDimension(0, 0f).toInt()
        styledAttributes.recycle()
        if (actionBarHeight == 0) {
            LogUtil.e(localClassName, "Can not get height of action bar")
        }
        return actionBarHeight
    }

    protected open fun virtualKeyHeight(): Int {
        val hasPermanentMenuKey = ViewConfiguration.get(application).hasPermanentMenuKey()
        if (hasPermanentMenuKey) {
            return 0
        }

        // Also can use getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        val metrics = DisplayMetrics()
        val display = windowManager.defaultDisplay
        display.getRealMetrics(metrics)
        var fullHeight = metrics.heightPixels
        var fullWidth = metrics.widthPixels
        if (fullHeight < fullWidth) {
            fullHeight = fullHeight xor fullWidth
            fullWidth = fullWidth xor fullHeight
            fullHeight = fullHeight xor fullWidth
        }
        display.getMetrics(metrics)
        var newFullHeight = metrics.heightPixels
        var newFullWidth = metrics.widthPixels
        if (newFullHeight < newFullWidth) {
            newFullHeight = newFullHeight xor newFullWidth
            newFullWidth = newFullWidth xor newFullHeight
            newFullHeight = newFullHeight xor newFullWidth
        }
        var virtualKeyHeight = fullHeight - newFullHeight
        if (virtualKeyHeight > 0) {
            return virtualKeyHeight
        }
        virtualKeyHeight = fullWidth - newFullWidth
        return virtualKeyHeight
    }

    fun closeIME(v: View) {
        val mgr = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        mgr.hideSoftInputFromWindow(v.windowToken, 0) // 0 force close IME
        v.clearFocus()
    }

    fun toast(content : String){
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show()
    }
}