package com.gh.gamecenter.personalhome.background

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.common.callback.BiCallback
import com.gh.gamecenter.common.utils.BitmapUtils
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.feature.entity.BackgroundImageEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File

class PersonalityBackgroundViewModel(application: Application) : AndroidViewModel(application) {

    val loadingLiveData = MutableLiveData<Boolean>()
    val backgroundImagesLiveData = MutableLiveData<ArrayList<BackgroundImageEntity>>()

    init {
        getBackgroundImages()
    }

    fun getBackgroundImages() {
        RetrofitManager.getInstance().api
            .backgroundImages
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ArrayList<BackgroundImageEntity>>() {
                override fun onResponse(response: ArrayList<BackgroundImageEntity>?) {
                    super.onResponse(response)
                    if (!response.isNullOrEmpty()) {
                        backgroundImagesLiveData.postValue(response)
                    }
                }
            })
    }

    @SuppressLint("CheckResult")
    fun downLoadImage(context: Context, entity: BackgroundImageEntity) {
        loadingLiveData.postValue(true)
        Single.just(entity.url)
            .flatMap {
                getBitmapFormCache(it)
            }
            .map {
                val fileName = entity.url.substring(entity.url.lastIndexOf("/") + 1)
                val filePath = "${context.cacheDir.absolutePath}${File.separator}$fileName"
                val file = File(filePath)
                if (!file.exists()) {
                    BitmapUtils.saveBitmap(it, filePath)
                }
                filePath
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                loadingLiveData.postValue(false)
                val intent = BackgroundPreviewActivity.getIntent(context, it, entity)
                (context as AppCompatActivity).startActivityForResult(
                    intent,
                    PersonalityBackgroundFragment.CHANGE_BACKGROUND_SUCCESS
                )
            }, {
                it.printStackTrace()
                loadingLiveData.postValue(false)
            })
    }

    private fun getBitmapFormCache(url: String): Single<Bitmap> {
        return Single.create {
            ImageUtils.getBitmap(url, object : BiCallback<Bitmap, Boolean> {
                override fun onFirst(first: Bitmap) {
                    it.onSuccess(first)
                }

                override fun onSecond(second: Boolean) {
                    it.onError(Throwable("获取bitmap失败"))
                }

            })
        }
    }
}