package com.hyphenate.chatdemo.ui.login

import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.hyphenate.chatdemo.BuildConfig
import com.hyphenate.chatdemo.DemoHelper
import com.hyphenate.chatdemo.R
import com.hyphenate.chatdemo.common.dialog.SimpleDialog
import com.hyphenate.chatdemo.common.extensions.internal.addDefaultTextChangedListener
import com.hyphenate.chatdemo.databinding.DemoFragmentServerSetBinding
import com.hyphenate.easeui.base.ChatUIKitBaseFragment
import kotlin.system.exitProcess

class ServerSetFragment: ChatUIKitBaseFragment<DemoFragmentServerSetBinding>() {

    private val changeArray = BooleanArray(10)
    private var isEnableCustomServer = false
    private var isEnableCustomServerTls = false

    private var isEnableRtcTokenVerify = false
    private var initialChatRestServerDomain = BuildConfig.CHAT_REST_SERVER_DOMAIN

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): DemoFragmentServerSetBinding? {
        return DemoFragmentServerSetBinding.inflate(inflater)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        binding?.toolbarServer?.let {
            it.inflateMenu(R.menu.demo_server_set_menu)
            enableSaveMenu(false)
        }
        binding?.etAppkey?.inputType = InputType.TYPE_CLASS_TEXT
        binding?.etChatRestServerDomain?.apply {
            inputType = InputType.TYPE_CLASS_TEXT
            initialChatRestServerDomain = DemoHelper.getInstance().getDataModel()
                .getChatRestServerDomain()
                .ifBlank { BuildConfig.CHAT_REST_SERVER_DOMAIN }
            setText(initialChatRestServerDomain)
        }
    }

    override fun initListener() {
        super.initListener()
        binding?.toolbarServer?.setNavigationOnClickListener {
            activity?.onBackPressed()
        }
        binding?.toolbarServer?.setOnMenuItemClickListener {
            when(it.itemId) {
                R.id.action_server_set_save -> {
                    saveSettings()
                    true
                }
                else -> false
            }
        }
        binding?.etAppkey?.addDefaultTextChangedListener {
            it?.let { s ->
                changeArray[0] = s.isNotEmpty()
                changeSaveMenu(s)
            }
        }
        binding?.etChatRestServerDomain?.addDefaultTextChangedListener {
            it?.let { s ->
                changeArray[9] = s.toString().trim() != initialChatRestServerDomain
                enableSaveMenu(checkChange())
            }
        }
        binding?.etServerAddress?.addDefaultTextChangedListener {
            it?.let { s ->
                changeArray[1] = s.isNotEmpty()
                changeSaveMenu(s)
            }
        }
        binding?.etServerPort?.addDefaultTextChangedListener {
            it?.let { s ->
                changeArray[2] = s.isNotEmpty()
                changeSaveMenu(s)
            }
        }
        binding?.etServerRest?.addDefaultTextChangedListener {
            it?.let { s ->
                changeArray[3] = s.isNotEmpty()
                changeSaveMenu(s)
            }
        }
        binding?.etRtcAppid?.addDefaultTextChangedListener {
            it?.let { s ->
                changeArray[4] = s.isNotEmpty()
                changeSaveMenu(s)
            }
        }
        binding?.etRtcIp?.addDefaultTextChangedListener {
            it?.let { s ->
                changeArray[5] = s.isNotEmpty()
                changeSaveMenu(s)
            }
        }
        binding?.etRtcDomain?.addDefaultTextChangedListener {
            it?.let { s ->
                changeArray[6] = s.isNotEmpty()
                changeSaveMenu(s)
            }
        }
        binding?.etWebsocketServer?.addDefaultTextChangedListener {
            it?.let { s ->
                changeArray[7] = s.isNotEmpty()
                changeSaveMenu(s)
            }
        }
        binding?.etWebsocketPort?.addDefaultTextChangedListener {
            it?.let { s ->
                changeArray[8] = s.isNotEmpty()
                changeSaveMenu(s)
            }
        }
        binding?.switchSpecifyServer?.setOnCheckedChangeListener { _, isChecked ->
            isEnableCustomServer = isChecked
            makeCustomServerItemEnable(isChecked)
        }

        binding?.switchEnablePrivateTls?.setOnCheckedChangeListener { _, isChecked ->
            isEnableCustomServerTls = isChecked
            DemoHelper.getInstance().getDataModel().enableCustomServerTls(isEnableCustomServerTls)
        }
        binding?.switchEnableRtcTokenVerify?.setOnCheckedChangeListener { _, isChecked ->
            isEnableRtcTokenVerify = isChecked
            DemoHelper.getInstance().getDataModel().enableRtcTokenVerify(isEnableRtcTokenVerify)
        }
    }

    private fun saveSettings() {
        if (checkChange()) {
            DemoHelper.getInstance().getDataModel().enableCustomSet(true)
            DemoHelper.getInstance().getDataModel().enableCustomServer(isEnableCustomServer)
            binding?.etAppkey?.text?.let {
                if (it.isNotEmpty()) {
                    val appkey = it.toString().trim()
                    if (appkey.contains("#")) {
                        DemoHelper.getInstance().getDataModel().setCustomAppKey(it.toString().trim())
                    } else {
                        checkAppkeyDialog()
                        return
                    }

                }else{
                    DemoHelper.getInstance().getDataModel().setCustomAppKey("")
                }
            }
            binding?.etChatRestServerDomain?.text?.let {
                DemoHelper.getInstance().getDataModel()
                    .setChatRestServerDomain(it.toString().trim())
            }
            binding?.etServerAddress?.text?.let {
                if (it.isNotEmpty()) {
                    DemoHelper.getInstance().getDataModel().setIMServer(it.toString().trim())
                }else{
                    DemoHelper.getInstance().getDataModel().setIMServer("")
                }
            }
            binding?.etServerPort?.text?.let {
                if (it.isNotEmpty()) {
                    DemoHelper.getInstance().getDataModel().setIMServerPort(it.toString().trim().toInt())
                }else{
                    DemoHelper.getInstance().getDataModel().setIMServerPort(0)
                }
            }
            binding?.etServerRest?.text?.let {
                if (it.isNotEmpty()) {
                    DemoHelper.getInstance().getDataModel().setRestServer(it.toString().trim())
                }else{
                    DemoHelper.getInstance().getDataModel().setRestServer("")
                }
            }
            binding?.etRtcAppid?.text?.let {
                if (it.isNotEmpty()) {
                    DemoHelper.getInstance().getDataModel().setRtcAppId(it.toString().trim())
                }else{
                    DemoHelper.getInstance().getDataModel().setRtcAppId("")
                }
            }
            binding?.etRtcIp?.text?.let {
                if (it.isNotEmpty()) {
                    DemoHelper.getInstance().getDataModel().setRtcIpAddress(it.toString().trim())
                }else{
                    DemoHelper.getInstance().getDataModel().setRtcIpAddress("")
                }
            }
            binding?.etRtcDomain?.text?.let {
                if (it.isNotEmpty()) {
                    DemoHelper.getInstance().getDataModel().setRtcVerifyDomain(it.toString().trim())
                }else{
                    DemoHelper.getInstance().getDataModel().setRtcVerifyDomain("")
                }
            }
            binding?.etWebsocketServer?.text?.let {
                if (it.isNotEmpty()) {
                    DemoHelper.getInstance().getDataModel().setWebSocketServer(it.toString().trim())
                }else{
                    DemoHelper.getInstance().getDataModel().setWebSocketServer("")
                }
            }
            binding?.etWebsocketPort?.text?.let {
                if (it.isNotEmpty()) {
                    DemoHelper.getInstance().getDataModel().setWebSocketPort(it.toString().trim().toInt())
                }else{
                    DemoHelper.getInstance().getDataModel().setWebSocketPort(0)
                }
            }
            if (isEnableCustomServer && checkServerSettingChange()) {
                showAlertDialog()
            } else {
                mContext.onBackPressed()
            }
        } else {
            DemoHelper.getInstance().getDataModel().enableCustomSet(false)
            mContext.onBackPressed()
        }
    }

    private fun showAlertDialog() {
        SimpleDialog.Builder(mContext)
            .setTitle(getString(R.string.server_set_dialog_title))
            .setSubtitle(getString(R.string.server_set_dialog_content))
            .setPositiveButton(getString(R.string.server_set_dialog_confirm_button_text)) {
                exitProcess(1)
            }
            .build()
            .show()
    }

    private fun checkAppkeyDialog() {
        SimpleDialog.Builder(mContext)
            .setTitle(getString(R.string.server_set_illegal_appkey))
            .setPositiveButton {
                // do nothing
            }
            .dismissNegativeButton()
            .build()
            .show()
    }

    override fun initData() {
        super.initData()
        DemoHelper.getInstance().getDataModel().isCustomSetEnable().let {
            if (it) {
                DemoHelper.getInstance().getDataModel().getCustomAppKey()?.let { appKey ->
                    binding?.etAppkey?.setText(appKey)
                }
                DemoHelper.getInstance().getDataModel().isCustomServerEnable().let { enable ->
                    isEnableCustomServer = enable
                    binding?.switchSpecifyServer?.isChecked = enable
                    makeCustomServerItemEnable(enable)
                }
                DemoHelper.getInstance().getDataModel().getIMServer()?.let { server ->
                    if (server.isEmpty().not()) {
                        binding?.etServerAddress?.setText(server)
                    }

                }
                DemoHelper.getInstance().getDataModel().getIMServerPort().let { port ->
                    if (port != 0) {
                        binding?.etServerPort?.setText(port.toString())
                    }
                }
                DemoHelper.getInstance().getDataModel().getRestServer()?.let { rest ->
                    if (rest.isEmpty().not()) {
                        binding?.etServerRest?.setText(rest)
                    }
                }
                DemoHelper.getInstance().getDataModel().getWebSocketServer()?.let { wsServer ->
                    if (wsServer.isEmpty().not()) {
                        binding?.etWebsocketServer?.setText(wsServer)
                    }
                }
                DemoHelper.getInstance().getDataModel().getWebSocketPort().let { wsPort ->
                    if (wsPort != 0) {
                        binding?.etWebsocketPort?.setText(wsPort.toString())
                    }
                }
                DemoHelper.getInstance().getDataModel().getRtcAppId()?.let { appId ->
                    if (appId.isEmpty().not()) {
                        binding?.etRtcAppid?.setText(appId)
                    }
                }
                DemoHelper.getInstance().getDataModel().getRtcIpAddress()?.let { ip ->
                    if (ip.isEmpty().not()) {
                        binding?.etRtcIp?.setText(ip)
                    }
                }
                DemoHelper.getInstance().getDataModel().getRtcVerifyDomain()?.let { domain ->
                    if (domain.isEmpty().not()) {
                        binding?.etRtcDomain?.setText(domain)
                    }
                }
            }
        }
        DemoHelper.getInstance().getDataModel().isCustomServerTlsEnable().let { enable ->
            isEnableCustomServerTls = enable
            binding?.switchEnablePrivateTls?.isChecked = enable
        }
        DemoHelper.getInstance().getDataModel().isRtcTokenVerifyEnable().let { enable ->
            isEnableRtcTokenVerify = enable
            binding?.switchEnableRtcTokenVerify?.isChecked = enable
        }
        makeCustomServerItemEnable(binding?.switchSpecifyServer?.isChecked ?: false)
    }

    private fun makeCustomServerItemEnable(enable: Boolean) {
        binding?.etServerAddress?.isEnabled = enable
        binding?.etServerPort?.isEnabled = enable
        binding?.etServerRest?.isEnabled = enable
        binding?.etWebsocketServer?.isEnabled = enable
        binding?.etWebsocketPort?.isEnabled = enable
        binding?.etRtcAppid?.isEnabled = enable
        binding?.etRtcIp?.isEnabled = enable
        binding?.etRtcDomain?.isEnabled = enable
    }

    private fun changeSaveMenu(s: Editable) {
        if (s.isNotEmpty()) {
            enableSaveMenu()
        } else {
            enableSaveMenu(checkChange())
        }
    }

    private fun checkChange(): Boolean {
        changeArray.forEach {
            if (it) {
                return true
            }
        }
        return false
    }

    private fun checkServerSettingChange(): Boolean {
        changeArray.forEachIndexed { index, b ->
            if (index in 1..8 && b) {
                return true
            }
        }
        return false
    }

    private fun enableSaveMenu(enable: Boolean = true) {
        binding?.toolbarServer?.let {
            if (enable) {
                it.setMenuTitleColor(ContextCompat.getColor(mContext, com.hyphenate.easeui.R.color.ease_color_primary))
            } else {
                it.setMenuTitleColor(ContextCompat.getColor(mContext, com.hyphenate.easeui.R.color.ease_color_on_background_high))
            }
        }

    }
}
