package com.dlc.exam.ui.login

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import androidx.viewbinding.ViewBinding
import com.dlc.exam.ExamApp
import com.dlc.exam.R
import com.dlc.exam.common.Constants
import com.dlc.exam.databinding.ActivityLoginBinding
import com.dlc.exam.ui.common.BaseCountDownActivity
import com.dlc.exam.ui.widget.TitleBar
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.httpcore.HttpClient
import java.lang.ref.WeakReference


/**
 * info
 *
 * @author ReiChin_
 */
class LoginActivity : BaseCountDownActivity<ActivityLoginBinding>(), LoginFragmentCallback,
    TitleBar.TitleListener {
    private val weakHandler by lazy { WeakReferenceHandler(this) }
    private val weakHandlerTwo by lazy { WeakReferenceHandlerTwo(this) }
    override fun createViewBinding() = ActivityLoginBinding.inflate(LayoutInflater.from(this))

    override fun initViews(savedInstanceState: Bundle?) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(
            R.id.container,
            StudentCardFragment.newInstance(),
            StudentCardFragment.FRAGMENT_TAG
        )
        transaction.commit()
    }

    override fun initListener() {
        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.showBackView(true)
    }

    override fun initData() {
        if (Constants.Mock.STUDENT_NUM_TEST) {
            weakHandler.sendEmptyMessageDelayed(1, 1500)
//            object : Handler(Looper.getMainLooper()) {
//
//                override fun handleMessage(msg: Message) {
//                    val fragment =
//                        supportFragmentManager.findFragmentByTag(StudentCardFragment.FRAGMENT_TAG)
//                                as? StudentCardFragment
//                    fragment?.let {
//                        if (it.isVisible) it.dispatchReadCardResult(Constants.Mock.STUDENT_NUM)
//                    }
//                }
//            }.sendEmptyMessageDelayed(1, 1500)
        }
    }

    override fun switchFragment(fragment: RcBaseFragment<out ViewBinding>) {
        val transaction = supportFragmentManager.beginTransaction()
//        val fragment = supportFragmentManager.findFragmentByTag(fragment.javaClass.simpleName)
        transaction.replace(R.id.container, fragment, fragment.javaClass.simpleName)

//        transaction.add(
//            R.id.container,
//            StudentCardFragment.newInstance(StudentCardFragment.SIGN_IN),
//            StudentCardFragment::class.java.simpleName
//        )
        transaction.commit()

        if (Constants.Mock.STUDENT_NUM_TEST && fragment is StudentCardFragment) {
            val msg: Message = Handler().obtainMessage()
            msg.obj = fragment
            weakHandlerTwo.sendMessage(msg)
            weakHandlerTwo.sendEmptyMessageDelayed(1, 1500)
//            object : Handler(Looper.getMainLooper()) {
//                override fun handleMessage(msg: Message) {
//            if (fragment.isVisible) fragment.dispatchReadCardResult(Constants.Mock.STUDENT_NUM)
//                }
//            }.sendEmptyMessageDelayed(1, 1500)
        }
    }


    // 仿真键盘输出内容
    private var keyContent = ""

    // 是否要取的标志。由于输出的值会重复发送一次，为防止重复接收，设置一个标志来判断是否要接收
    private var fGet = true

    // 将键值转成对应的ASCII码
    private fun getCharByKeyCode(keyCode: Int): Char {
        var outChar = 0.toChar()
        if (keyCode in 7..16) //数字
            outChar = (keyCode - 7 + 0x30).toChar()
        if (keyCode in 29..54) //字母
            outChar = (keyCode - 29 + 0x41).toChar()
        return outChar
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        // 在这里监控键盘输出的键值
        if (event!!.keyCode == KeyEvent.KEYCODE_ENTER) {
            if (keyContent.isNotEmpty()) {
                val fragment =
                    supportFragmentManager.findFragmentByTag(StudentCardFragment.FRAGMENT_TAG)
                            as? StudentCardFragment
                fragment?.let {
                    if (it.isVisible) it.dispatchReadCardResult(keyContent)
                }
            }
            keyContent = ""
        } else {
            val keyCode = event.keyCode
            if (fGet) {
                keyContent += getCharByKeyCode(keyCode)
                fGet = false
            } else fGet = true
        }
        return super.dispatchKeyEvent(event)
    }

    override fun onBackPressed() {
        ExamApp.sLearnLoginVo = null
        HttpClient.token = null
        super.onBackPressed()
    }

    override fun onHomeViewClicked(view: View) {
    }

    override fun onLogoutViewClicked(view: View) {
    }

    override fun onBackViewClicked(view: View) {
        onBackPressed()
    }

    override fun onUserViewClicked(view: View) {
    }

    // static + 弱引用  防止内存泄露
    class WeakReferenceHandler(obj: LoginActivity) : Handler(Looper.getMainLooper()) {
        private val mRef: WeakReference<LoginActivity> = WeakReference(obj)
        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                val fragment =
                    supportFragmentManager.findFragmentByTag(StudentCardFragment.FRAGMENT_TAG)
                            as? StudentCardFragment
                fragment?.let {
                    if (it.isVisible) it.dispatchReadCardResult(Constants.Mock.STUDENT_NUM)
                }
            }
        }
    }

    // static + 弱引用  防止内存泄露
    class WeakReferenceHandlerTwo(obj: LoginActivity) : Handler(Looper.getMainLooper()) {
        private val mRef: WeakReference<LoginActivity> = WeakReference(obj)

        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                val fragment = msg.obj as StudentCardFragment
                if (fragment.isVisible) fragment.dispatchReadCardResult(Constants.Mock.STUDENT_NUM)
            }
        }
    }
}