package com.develop.setting.ui

import android.content.Context
import android.os.Bundle
import android.os.PowerManager
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.appcompat.widget.AppCompatTextView
import com.develop.base.ext.load
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LanguageUtils
import com.develop.base.ext.navigateTo
import com.develop.base.ext.resId2Dimension
import com.develop.base.ext.updateText
import com.develop.base.mvvm.BaseBindingActivity
import com.develop.base.util.MMkvUtils
import com.develop.common.data_repo.db.DataFactory
import com.develop.common.data_repo.db.LanguageModel
import com.develop.common.event.FinishAtyEvent
import com.develop.common.router.Screens
import com.develop.common.tag.*
import com.develop.common.dialog.CancelConfirmDialog
import com.develop.setting.R
import com.develop.setting.databinding.ActivityLanguageBinding
import com.drake.brv.utils.bindingAdapter
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevStatus
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK
import org.greenrobot.eventbus.Subscribe
import java.util.*

@Route(path = Screens.Setting.LANGUAGE)
class LanguageActivity : BaseBindingActivity<ActivityLanguageBinding>() {
    private val cancelConfirmDialog by lazy {
        CancelConfirmDialog()
    }
    private var selectedPosition = -1
    private var isLanguageTip = false

    override fun createViewBinding(inflater: LayoutInflater): ActivityLanguageBinding {
        return ActivityLanguageBinding.inflate(inflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val isFromSetting = intent.extras?.getBoolean(LANGUAGE_FROM_SETTING) ?: false
        if (isFromSetting) {
            binding.apply {
                ivBanner.visibility = View.GONE
                tvLanguage.visibility = View.GONE
//                ivLogo.visibility = View.GONE
                ivClose.visibility = View.VISIBLE
                tvTitle.visibility = View.VISIBLE
                ivClose.setOnClickListener {
                    finish()
                }
                tvTitle.updateText(getString(com.develop.common.R.string.language))
                val params = languageRecycle.layoutParams as RelativeLayout.LayoutParams
                params.topMargin = dp81
                params.marginStart = dp310
                params.marginEnd = dp310
                languageRecycle.layoutParams = params
                val nextParam = tvNext.layoutParams as RelativeLayout.LayoutParams
                nextParam.marginStart = dp310
                nextParam.marginEnd = dp310
                tvNext.layoutParams = nextParam
                tvNext.updateText(getString(com.develop.common.R.string.confirm))
            }
        }

        binding.languageRecycle.apply {
            linear()
            setup {
                addType<LanguageModel>(R.layout.item_language_view)
                onBind {
                    val ivIcon = findView<ImageView>(R.id.ic_icon)
                    val tvTitle = findView<AppCompatTextView>(R.id.tv_title)
                    val cardView = findView<RelativeLayout>(R.id.content_layout)
                    if (selectedPosition == absoluteAdapterPosition) {
                        tvTitle.setTextColor(context.resources.getColor(com.develop.common.R.color.color_EE8F08))
                        cardView.setBackgroundResource(com.develop.common.R.drawable.shape_44pxfff6e9_stoke)
                    } else {
                        tvTitle.setTextColor(context.resources.getColor(com.develop.common.R.color.color_1A1A1A))
                        cardView.setBackgroundResource(com.develop.common.R.drawable.shape_44pxffffff_stoke)
                    }
                    val model = getModel<LanguageModel>()
                    ivIcon.load(model.icon)
                    tvTitle.updateText(model.languageName)
                }
                R.id.content_layout.onClick {
                    updateSelectionPos(absoluteAdapterPosition)
                }
            }
        }.models = DataFactory.createLanguageData(resources)

        selectedPosition = getSelectedPos()

        cancelConfirmDialog.onDialogClickListener =
            object : CancelConfirmDialog.OnDialogClickListener {
                override fun onConfirm() {
                    if (isLanguageTip) {
                        updateLanguage()
//                        navigateTo(Screens.Main.ENTRANCE_CHOSEN)
//                        finish()
                        val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
                        pm.reboot("")
                    }
                }

                override fun onCancel() {

                }

            }

        binding.tvNext.setOnClickListener {
            if (CofarSDK.devInfo().status == DevStatus.RUNNING.toInt()) {
                isLanguageTip = false
                cancelConfirmDialog.title = getString(com.develop.common.R.string.change_lang_tips)
                cancelConfirmDialog.apply {
                    showCancel = false
                    showDialog(supportFragmentManager, "confirm")
                }
                return@setOnClickListener
            }
            if (isFromSetting) {
                if(binding.languageRecycle.models?.size!! > 1){
                    isLanguageTip = true
                    cancelConfirmDialog.title = getString(com.develop.common.R.string.change_lang_tips2)
                    cancelConfirmDialog.showDialog(supportFragmentManager, "tips2")
                }else{
                    finish()
                }

            } else {
                updateLanguage()
                navigateTo(Screens.Setting.POLICY)
            }
        }

    }

    private fun updateSelectionPos(pos: Int) {
        val tempPosition = selectedPosition
        selectedPosition = pos
        binding.languageRecycle.bindingAdapter.apply {
            notifyItemChanged(tempPosition)
            notifyItemChanged(selectedPosition)
        }
    }

    private fun updateLanguage() {
        when (selectedPosition) {
            0, -1 -> {
                MMkvUtils.save(CURRENT_LANGUAGE, EN)
                LanguageUtils.applyLanguage(Locale.ENGLISH)
            }
            1 -> {
                MMkvUtils.save(CURRENT_LANGUAGE, FR)
                LanguageUtils.applyLanguage(Locale.FRANCE)

            }
            2 -> {
                MMkvUtils.save(CURRENT_LANGUAGE, ZH)
                LanguageUtils.applyLanguage(Locale.CHINESE)
            }
            3 -> {
                MMkvUtils.save(CURRENT_LANGUAGE, JA)
                LanguageUtils.applyLanguage(Locale.JAPAN)
            }
        }
    }

    private fun getSelectedPos(): Int {
        return when (MMkvUtils.getString(CURRENT_LANGUAGE)) {
            EN -> {
                updateSelectionPos(0)
                0
            }
            ZH -> {
                updateSelectionPos(1)
                1
            }

            FR -> {
                updateSelectionPos(2)
                2
            }

            JA -> {
                updateSelectionPos(3)
                3
            }
            else -> {
                updateSelectionPos(0)
                0
            }
        }
    }

    @Subscribe
    fun onFinishAtyEvent(event: FinishAtyEvent) {
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()

        cancelConfirmDialog.removeSelf()
    }

    companion object {
        var dp81 = (com.develop.base.R.dimen.convert_81px).resId2Dimension().toInt()
        var dp310 = (com.develop.base.R.dimen.convert_310px).resId2Dimension().toInt()
        var dp6 = (com.develop.base.R.dimen.convert_6px).resId2Dimension()
    }

}