package com.adealink.weparty.commonui.toast.util

import android.widget.Toast
import androidx.annotation.StringRes
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.AppBase
import com.adealink.frame.base.IError
import com.adealink.frame.base.Rlt
import com.adealink.frame.util.AppUtil
import com.adealink.frame.util.runOnUiThread
import com.adealink.weparty.BuildConfig
import com.adealink.weparty.R
import com.adealink.weparty.commonui.toast.ToastCompat

fun showToast(text: CharSequence) {
    showToast(text, Toast.LENGTH_SHORT)
}

fun showToast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT, style: ToastCompat.Style = ToastCompat.Style.TEXT) {
    runOnUiThread {
        ToastCompat.show(
            AppUtil.appContext,
            text = text.toString(),
            position = ToastCompat.Position.CENTER,
            duration = ToastCompat.Duration.map(duration),
            style = style
        )
    }
}

fun showToast(@StringRes resId: Int) {
    showToast(resId, Toast.LENGTH_SHORT)
}

fun showToast(@StringRes resId: Int, duration: Int, style: ToastCompat.Style = ToastCompat.Style.TEXT) {
    runOnUiThread {
        showToast(getCompatString(resId), duration = duration, style = style)
    }
}

fun showToast(rlt: Rlt<*>?) {
    when (rlt) {
        is Rlt.Success -> {
            showToast(getCompatString(R.string.common_success))
        }

        is Rlt.Failed -> {
            showFailedToast(rlt)
        }

        else -> {
            showToast(getCompatString(R.string.common_failed))
        }
    }
}

fun showFailedToast(rlt: Rlt<*>) {
    if (rlt is Rlt.Failed) {
        showToast(rlt.error, getCompatString(R.string.common_failed))
    }
}

fun showToast(error: IError, default: CharSequence? = null) {
    if (error.msg.isNotEmpty()) {
        if (AppBase.isRelease) {
            //正式包不展示错误码
            showToast(error.msg)
        } else {
            showToast(getCompatString(R.string.commonui_error_msg, error.msg, error.serverCode))
        }
        return
    }

    if (error.exception?.message?.isNotBlank() == true) {
        showToast(error.exception!!.message!!)
        return
    }

    if (default.isNullOrEmpty()) {
        return
    }

    showToast(default)
}

fun getFailedMsg(error: IError, default: String? = getCompatString(R.string.common_failed)): String {
    if (error.msg.isNotEmpty()) {
        return if (AppBase.isRelease) {
            error.msg
        } else {
            getCompatString(R.string.commonui_error_msg, error.msg, error.serverCode)
        }
    }

    val exceptionMsg = error.exception?.message
    if (exceptionMsg?.isNotBlank() == true) {
        return exceptionMsg
    }

    if (default.isNullOrEmpty()) {
        return ""
    }

    return default
}

fun debugToast(msg: String) {
    if (BuildConfig.DEBUG) {
        showToast("DEBUG: $msg", Toast.LENGTH_LONG)
    }
}