package com.develop.common.utils

import com.azhon.appupdate.util.LogUtil
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ZipUtils
import com.develop.base.ext.fromJson
import com.develop.base.util.FileKit
import com.develop.base.util.TopResumedAtyHolder
import com.develop.common.data_repo.FoodDataProvider
import com.develop.common.data_repo.db.entity.DevVersion
import com.develop.common.data_repo.net.Api
import com.develop.common.data_repo.net.model.request.DeviceInfoBody
import com.develop.common.data_repo.net.model.response.DevInfoResult
import com.develop.common.data_repo.net.model.response.RecipeDataConfig
import com.develop.common.dialog.RecipeUpdateDialog
import com.drake.net.Get
import com.drake.net.Post
import com.drake.net.component.Progress
import com.drake.net.interfaces.ProgressListener
import com.drake.net.utils.scopeNetLife
import java.io.File
import java.util.*

object AppVersionUtil {

    fun checkRecipeUpdate(shoNoUpdateDialog: Boolean = false) {

        TopResumedAtyHolder.getCurrentActivity()?.apply {
            scopeNetLife {

                try {
                    val result = Post<DevInfoResult>(Api.DEV_INFO) {
                        body = DeviceInfoBody.genDeviceInfoBody()
                    }.await()
                    val downloadDir = this@apply.externalCacheDir.toString()
                    val downloadName = System.nanoTime().toString()
                    val recipeUpdateTime = result.recipeUpdateTime
                    val newRecipes = LinkedList(result.newRecipes)
                    if (newRecipes.isEmpty() && shoNoUpdateDialog) {
                        val dialog = RecipeUpdateDialog()
                        dialog.onDialogClickListener =
                            object : RecipeUpdateDialog.OnDialogClickListener {
                                override fun onConfirm() {

                                }

                                override fun onCancel() {
                                }
                            }
                        dialog.showNoUpdateTips(supportFragmentManager, "RECIPE_UPDATE_DIALOG")

                    }
                    if (newRecipes.isNotEmpty()) {
                        val dialog = RecipeUpdateDialog()
                        dialog.onDialogClickListener =
                            object : RecipeUpdateDialog.OnDialogClickListener {
                                override fun onConfirm() {
                                    downloadRecipes(
                                        newRecipes,
                                        dialog,
                                        newRecipes.size.toLong(),
                                        downloadDir,
                                        downloadName,
                                        recipeUpdateTime
                                    )
                                }

                                override fun onCancel() {
                                }

                            }
                        dialog.showUpdateTips(
                            supportFragmentManager, "RECIPE_UPDATE_DIALOG", newRecipes.size.toLong()
                        )
                    }
                }catch (e:java.lang.Exception){
                    e.printStackTrace()
                }


            }

        }
    }

    private fun downloadRecipes(
        newRecipes: LinkedList<String>,
        recipeUpdateDialog: RecipeUpdateDialog,
        sum: Long,
        downloadDir: String,
        downloadName: String,
        recipeUpdateTime: Long?
    ) {
        TopResumedAtyHolder.getCurrentActivity()?.apply {
            if (newRecipes.isEmpty()) {
                recipeUpdateDialog.removeSelf()
                showRecipesUpdateDialog(recipeUpdateTime)
                return
            }
            val recipeUrl = newRecipes.pop()
            val recipeNumber = recipeUrl.split("@")[0]
            val fileUrl = recipeUrl.split("@")[1]
            recipeUpdateDialog.showUpdating(supportFragmentManager, "", sum - newRecipes.size, sum)
            scopeNetLife {
                val result = Get<File>(fileUrl) {
                    setDownloadFileName(downloadName)
                    setDownloadDir(downloadDir)
                    addDownloadListener(object : ProgressListener() {
                        override fun onProgress(p: Progress) {
                            LogUtil.d("dddddd", p.toString())
                        }
                    })
                }.await()
                if (!result.exists()) {
                    downloadRecipes(
                        newRecipes,
                        recipeUpdateDialog,
                        sum,
                        downloadDir,
                        downloadName,
                        recipeUpdateTime
                    )
                } else {
                    prepareResource(result, recipeNumber)
                    downloadRecipes(
                        newRecipes,
                        recipeUpdateDialog,
                        sum,
                        downloadDir,
                        downloadName,
                        recipeUpdateTime
                    )
                }
            }
        }
    }

    private fun prepareResource(file: File, recipeNumber: String) {
        try {
            val dst = ZipUtils.unzipFile(file, FoodDataProvider.getExtRecipeResourceDir())
            FileUtils.delete(file)
            if (dst.isNullOrEmpty()) {

                return
            }
            val jsonFile = FoodDataProvider.getResourceConfigJsonPath(recipeNumber)
            if (!jsonFile.exists()) {
                return
            }
            val jsonContent = FileKit.readFileToString(jsonFile)
            val contentData = jsonContent.fromJson() as RecipeDataConfig
            contentData.resetAllCodes()
            FoodDataProvider.getDatabase().runInTransaction {
                FoodDataProvider.getDatabase().recipeDao().apply {

                    deleteDevRecipeAccessorys(recipeNumber)
                    deleteDevRecipeCookingSteps(recipeNumber)
                    deleteDevRecipeFoods(recipeNumber)
                    deleteDevRecipeNutritions(recipeNumber)
                    deleteDevRecipeRelTags(recipeNumber)
                    deleteDevRecipePortionSizes(recipeNumber)
                    deleteRecipe(recipeNumber)

                    insertDevAccessorys(contentData.devAccessorys)
                    insertHotTags(contentData.devHotTags)
                    insertDevPortraits(contentData.devPortraits)
                    insertDevRecipeAccessorys(contentData.devRecipeAccessorys)
                    insertDevRecipeCategorys(contentData.devRecipeCategorys)
                    insertDevRecipeCookingSteps(contentData.devRecipeCookingSteps)
                    insertDevRecipeFoods(contentData.devRecipeFoods)
                    insertDevRecipeNutritions(contentData.devRecipeNutritions)
                    insertDevRecipePortionSizes(contentData.devRecipePortionSizes)
                    insertDevRecipeRelTags(contentData.devRecipeRelTags)
                    insertDevRecipeTags(contentData.devRecipeTags)
                    insertDevRecipes(contentData.devRecipes)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    private fun showRecipesUpdateDialog(recipeUpdateTime: Long?) {
        TopResumedAtyHolder.getCurrentActivity()?.apply {
            RecipeUpdateDialog().apply {
                onDialogClickListener = object : RecipeUpdateDialog.OnDialogClickListener {
                    override fun onConfirm() {
                        val v = FoodDataProvider.getUserDatabase().devConfigDao().recipeVersion()
                            ?: DevVersion(0, 0)
                        v.recipeUpdateTime = recipeUpdateTime
                        FoodDataProvider.getUserDatabase().devConfigDao().saveDevVersion(v)
                        removeSelf()
                    }

                    override fun onCancel() {

                    }

                }
                showSuccess(supportFragmentManager, "recipeUpdateDialog")
            }
        }
    }
}