package com.aiosman.riderpro.ui.account

import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.UploadImage
import com.aiosman.riderpro.entity.AccountProfileEntity
import com.aiosman.riderpro.ui.index.tabs.profile.MyProfileViewModel
import java.io.File

object AccountEditViewModel : ViewModel() {
    var name by mutableStateOf("")
    var bio by mutableStateOf("")
    var imageUrl by mutableStateOf<Uri?>(null)
    val accountService: AccountService = AccountServiceImpl()
    var profile by mutableStateOf<AccountProfileEntity?>(null)
    var croppedBitmap by mutableStateOf<Bitmap?>(null)
    suspend fun reloadProfile() {
        accountService.getMyAccountProfile().let {
            profile = it
            name = it.nickName
            bio = it.bio
        }
    }

    suspend fun updateUserProfile(context: Context) {

        val newAvatar = croppedBitmap?.let {
            val file = File(context.cacheDir, "avatar.jpg")
            it.compress(Bitmap.CompressFormat.JPEG, 100, file.outputStream())
            UploadImage(file, "avatar.jpg", "", "jpg")
        }
        val newName = if (name == profile?.nickName) null else name
        accountService.updateProfile(
            avatar = newAvatar,
            banner = null,
            nickName = newName,
            bio = bio
        )
        // 刷新用户资料
        reloadProfile()
        // 刷新个人资料页面的用户资料
        MyProfileViewModel.loadUserProfile()

    }
}