package com.casic.detector.extensions

import com.casic.detector.model.ErrorMessageModel
import com.casic.detector.utils.FileType
import com.casic.detector.utils.LocaleConstant
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.pengxh.kt.lite.utils.SaveKeyValues
import org.json.JSONObject

/**
 * String扩展方法
 */
fun String.separateResponseState(): Boolean {
    if (this.isBlank()) {
        return false
    }
    return JSONObject(this).getBoolean("success")
}

fun String.toErrorMessage(): String {
    val errorModel = Gson().fromJson<ErrorMessageModel>(
        this, object : TypeToken<ErrorMessageModel>() {}.type
    )
    return errorModel.message.toString()
}

/**
 * 下载路径为 http://xx.com/static/ 拼接downloadUrl
 * */
fun String.appendDownloadUrl(type: FileType): String {
    if (this.isEmpty()) return this
    val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
    val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
    val httpConfig = "http://${serverIp}:${serverPort}"
    return when (type) {
        FileType.APK -> "$httpConfig/ems/${this}"
        FileType.EXCEL -> "$httpConfig/ems/xls/marker${this}.xls"
    }
}