package com.develop.food.base.utils

import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ZipUtils
import com.develop.food.base.api.FoodRepository
import com.develop.food.base.api.response.RecipeDataConfig
import com.develop.food.base.http.observeStatus
import com.develop.food.base.repo.FoodDataProvider
import com.develop.food.base.repo.entity.DevVersion
import com.develop.food.base.widgets.RecipeUpdateDialog
import com.google.gson.Gson
import java.io.File
import java.util.*

object AppVerUtils {

    fun checkRecipeUpdate(empty: Boolean =false){

        FoodRepository.devInfo().observeStatus(onSuccess = {
            print(it?.newRecipes)
            if(it?.newRecipes?.size!! > 0){
                TopResumedActivityHolder.getCurrentActivity()?.apply {
                    val dialog = RecipeUpdateDialog()
                    dialog.onDialogClickListener = object : RecipeUpdateDialog.OnDialogClickListener{
                        override fun onConfirm() {
                            val recipeUrls = LinkedList(it?.newRecipes)
                            val dialog = RecipeUpdateDialog();
                            downloadRecipe(recipeUrls,it?.newRecipes.size.toLong(),dialog,it.recipeUpdateTime)
                        }

                        override fun onCancel() {
                        }

                    }
                    dialog.showUpdateTips(supportFragmentManager,"RECIPE_UPDATE_DIALOG",it.newRecipes.size.toLong())

                }
            }else if (empty){


                TopResumedActivityHolder.getCurrentActivity()?.apply {
                    val dialog = RecipeUpdateDialog()
                    dialog.onDialogClickListener = object : RecipeUpdateDialog.OnDialogClickListener{
                        override fun onConfirm() {

                        }

                        override fun onCancel() {
                        }

                    }

                    dialog.showNoUpdateTips(supportFragmentManager,"RECIPE_UPDATE_DIALOG")


                }


            }

        })

    }

    private fun downloadRecipe(recipeUrls:LinkedList<String>,sum:Long,dialog: RecipeUpdateDialog,recipeUpdateTime:Long){

        TopResumedActivityHolder.getCurrentActivity()?.apply {
            val downloadDir = this.externalCacheDir.toString()
            val downloadName = System.nanoTime().toString()
            if(recipeUrls.isEmpty()){
                dialog.dismissAllowingStateLoss()
                val success = RecipeUpdateDialog();
                success.showSuccess(supportFragmentManager,"xx")
                success.onDialogClickListener = object:RecipeUpdateDialog.OnDialogClickListener{
                    override fun onConfirm() {
                        var v =  FoodDataProvider.getUserDatabase().devConfigDao().recipeVersion()
                        if(v == null){
                            v = DevVersion(1,recipeUpdateTime)
                        }
                        v.recipeUpdateTime = recipeUpdateTime
                        FoodDataProvider.getUserDatabase().devConfigDao().saveDevVersion(v)

                    }

                    override fun onCancel() {
                    }

                }
                return
            }
            val recipeUrl = recipeUrls.pop()
            val recipeNumber = recipeUrl.split("@")[0]
            val fileUrl = recipeUrl.split("@")[1]
            dialog.showUpdating(supportFragmentManager,"" ,sum - recipeUrls.size,sum)

            DownloadUtil.get().download(fileUrl, downloadDir, downloadName,
                object : DownloadUtil.OnDownloadListener {
                    override fun onDownloadSuccess(file: File) {
                        prepareResource(file,recipeNumber)
                        downloadRecipe(recipeUrls,sum,dialog,recipeUpdateTime)
                    }

                    override fun onDownloading(progress: Int) {
                        println(progress)
                    }

                    override fun onDownloadFailed(e: Exception?) {
                        downloadRecipe(recipeUrls,sum,dialog,recipeUpdateTime)
                        println(e)
                    }
                })
        }


    }

    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 = Gson().fromJson(jsonContent, RecipeDataConfig::class.java)
            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()
        }
    }

}