package com.img.rabbit.utils

import android.text.TextUtils
import com.img.rabbit.BuildConfig
import com.img.rabbit.bean.response.VersionEntity

object AppUpdate {
    fun checkUpdate(versionInfo: VersionEntity?, onResult: (isUpdate: Boolean, tips: String) -> Unit) {

        if(versionInfo == null){
            onResult.invoke(false, "已是最新版本")
            return
        }
        versionInfo.apply {
            if (checkVersion(version, BuildConfig.VERSION_NAME)) {
                if (last_version_force == BuildConfig.VERSION_NAME) {
                    force = true
                } else if (checkVersion(last_version_force, BuildConfig.VERSION_NAME)) {
                    force = true
                }
                onResult.invoke(true, "检测到新版本")
                //提示执行更新
                //startUpdate(result, fragment)
            } else {
                onResult.invoke(false, "当前版本为最新版本")
            }
        }
    }

    private fun checkVersion(version: String, origin: String): Boolean {
        if (TextUtils.isEmpty(version) || TextUtils.isEmpty(origin)) {
            return false
        }
        val versions = version.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        val origins = origin.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        if (versions.size != 3) {
            return false
        }
        if (origins.size != 3) {
            return false
        }
        for (i in 0..2) {
            if (versions[i].toInt() > origins[i].toInt()) {
                return true
            } else if (versions[i].toInt() < origins[i].toInt()) {
                return false
            }
        }
        return false
    }
}