package com.cretin.translatetools.config

import com.cretin.translatetools.entity.ConfigJson
import com.cretin.translatetools.utils.GsonGet
import org.apache.http.util.TextUtils
import java.io.File

object ConfigHelper {
    /**
     * 获取配置文件
     */
    private fun getConfigFile(): File? {
        return try {
            var jarPath = System.getProperty("java.class.path")
            jarPath = jarPath.substring(0, jarPath.lastIndexOf("/"))
            val file = File("$jarPath/cm_translate_v2.conf")
            if (!file.exists()) {
                file.createNewFile()
            }
            file
        } catch (e: Exception) {
            null
        }
    }

    fun getConfigHost(): String {
        if (Config.IS_DEBUG) {
            return Config.HOST
        }
        return getConfig().host
    }

    fun getConfigAdmin(): String {
        if (Config.IS_DEBUG) {
            return Config.HOST_ADMIN
        }
        return getConfig().admin
    }

    fun writeConfigClient(clientType: Int) {
        if (!Config.IS_DEBUG)
            getConfig()?.apply {
                this.clientType = clientType
                getConfigFile()?.writeText(GsonGet.getGson().toJson(this))
            }
    }

    fun writeConfigVersion(version: String) {
        if (!Config.IS_DEBUG)
            getConfig()?.apply {
                this.version = version
                getConfigFile()?.writeText(GsonGet.getGson().toJson(this))
            }
    }

    fun writeConfigToken(token: String) {
        if (!Config.IS_DEBUG)
            getConfig()?.apply {
                this.token = token
                getConfigFile()?.writeText(GsonGet.getGson().toJson(this))
            }
    }

    fun writeConfigRootPath(rootPath: String) {
        if (!Config.IS_DEBUG)
            getConfig()?.apply {
                this.rootPath = rootPath
                getConfigFile()?.writeText(GsonGet.getGson().toJson(this))
            }
    }

    /**
     * 获取配置
     */
    fun getConfig(): ConfigJson {
        if (!Config.IS_DEBUG) {
            val file = getConfigFile()
            val content = file?.readText() ?: ""
            return if (TextUtils.isEmpty(content)) {
                ConfigJson.createNew()
            } else {
                try {
                    GsonGet.getGson().fromJson(content, ConfigJson::class.java)
                } catch (e: Throwable) {
                    ConfigJson.createNew()
                }
            }
        } else {
            return ConfigJson(1, "/Users/cretin/Downloads/ios_translate/zh-Hans.lproj", "43822f8e981141ec9bf322f5aa6bbacb")
        }
    }
}