package com.zswc.creativity.base

import android.content.Context
import android.os.IBinder
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.databinding.ViewDataBinding
import com.zswc.creativity.R
import com.zswc.creativity.activity.OneLoginActivity
import com.zswc.creativity.model.User
import com.ysnows.base.base.BActivity
import com.ysnows.base.base.BViewModel
import com.ysnows.base.inter.IUser
import com.ysnows.base.utils.UiSwitch

/**
 * Mine Base Activity
 *
 * @param <VM>
 * @param <B>
</B></VM> */
abstract class MBActivity<VM : BViewModel<*>, B : ViewDataBinding> : BActivity<VM, B>() {
    override fun toLogin() {
        super.toLogin()
//        toast(R.string.please_login)
        UiSwitch.single(context(), OneLoginActivity::class.java)
    }

    override fun user(): IUser? {
        return User.get()
    }

    override fun bgColor(): Int {
        return R.color.white
    }

    override fun titleColor(): Int {
        return R.color.black
    }

    override fun rightTextColor(): Int {
        return R.color.black
    }

    override fun backDrawable(): Int {
        return R.drawable.ic_back_black
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev!!.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v!!.windowToken)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
      fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
      fun hideKeyboard(token: IBinder?) {
        if (token != null) {
            val im = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }
}
