package com.ypsx.yppos.kit

import android.app.Activity
import android.content.Context
import androidx.appcompat.app.AlertDialog
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.input.InputCallback
import com.afollestad.materialdialogs.input.input
import com.afollestad.materialdialogs.list.SingleChoiceListener
import com.afollestad.materialdialogs.list.listItemsSingleChoice
import com.didichuxing.doraemonkit.kit.AbstractKit
import com.didichuxing.doraemonkit.util.ActivityUtils
import com.ypsx.yppos.PosApp
import com.ypsx.yppos.R
import com.ypsx.yppos.room.database.PosDatabase
import com.ypsx.yppos.utils.CacheUtil

class ServerHostKit : AbstractKit() {
    private val hostMap = mapOf(
        "sit开发环境Host" to "https://sit-cpos.ypshengxian.com/",
        "预发Host" to "https://pre-cpos.ypshengxian.com/",
        "线上正式Host" to "https://cpos.ypshengxian.com/",
    )

    private val hosts = hostMap.values.toTypedArray()
    private val names = hostMap.keys.toList()
    override val icon: Int
        get() = R.mipmap.icon_yp_logo
    override val name: Int
        get() = R.string.environment_kit

    override fun onClickWithReturn(activity: Activity): Boolean {
        val activity = ActivityUtils.getTopActivity()

        //选中的host
        val checkHost =
            CacheUtil.getHost()
        var checkedIndex = hosts.indexOf(checkHost)
        if (checkedIndex < 0) checkedIndex = names.size - 1//也就是研发Native那个
        //启用输入的host
        MaterialDialog(activity).title(text = "切换Server接口")
            .cancelable(false)
            .cancelOnTouchOutside(false)
            .listItemsSingleChoice(
                items = names,
                initialSelection = checkedIndex,
                selection = object : SingleChoiceListener {
                    override fun invoke(dialog: MaterialDialog, index: Int, text: CharSequence) {
                        //如果选择了研发native，index就会超过host的index
                        if (index < hosts.size) {
                            CacheUtil.setHost(hosts[index])
                            CacheUtil.clearAll()
                            PosDatabase.clearAllTables()
                            PosApp.instance.restartApplication()
                        }
                    }
                })
            .positiveButton(text = "确定")
            .negativeButton(text = "取消")
            .show()
        return true
    }

    override fun onAppInit(context: Context?) {

    }

}