package com.adealink.weparty.imageselect.clip

import android.graphics.Bitmap
import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.frame.util.AppUtil
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException

internal class BitmapViewModel : BaseViewModel() {

    private val _bitmap = MutableLiveData<Bitmap>()
    val bitmap: LiveData<Bitmap> = _bitmap

    private val _saveBitmapResult = MutableLiveData<Boolean>()
    val saveBitmapResult: LiveData<Boolean> = _saveBitmapResult

    fun saveBitmap(bitmap: Bitmap, saveTo: Uri) {
        viewModelScope.launch {
            try {
                val success = doSaveBitmap(bitmap, saveTo)
                _saveBitmapResult.setValue(success)
            } catch (e: IOException) {
                _saveBitmapResult.setValue(false)
            }
        }
    }

    private suspend fun doSaveBitmap(bitmap: Bitmap, saveTo: Uri): Boolean {
        return withContext(Dispatcher.WENEXT_THREAD_POOL) {
            val contentResolver = AppUtil.appContext.contentResolver
            try {
                val out = contentResolver.openOutputStream(saveTo)
                if (out == null) {
                    bitmap.recycle()
                    return@withContext false
                }
                out.use {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
                }
                bitmap.recycle()
                return@withContext true
            } catch (e: Exception) {
                bitmap.recycle()
                return@withContext false
            }
        }
    }
}
