package com.aiosman.riderpro.ui.post

import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.aiosman.riderpro.data.MomentService
import com.aiosman.riderpro.entity.MomentServiceImpl
import com.aiosman.riderpro.data.UploadImage
import com.aiosman.riderpro.entity.MomentEntity
import com.aiosman.riderpro.ui.index.tabs.moment.MomentViewModel
import com.aiosman.riderpro.ui.index.tabs.profile.MyProfileViewModel
import com.aiosman.riderpro.ui.modification.Modification
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream


object NewPostViewModel : ViewModel() {
    var momentService: MomentService = MomentServiceImpl()
    var textContent by mutableStateOf("")
    var searchPlaceAddressResult by mutableStateOf<SearchPlaceAddressResult?>(null)
    var modificationList by mutableStateOf<List<Modification>>(listOf())
    var imageUriList by mutableStateOf(listOf<String>())
    var relPostId by mutableStateOf<Int?>(null)
    var relMoment by mutableStateOf<MomentEntity?>(null)
    var currentPhotoUri: Uri? = null
    fun asNewPost() {
        textContent = ""
        searchPlaceAddressResult = null
        modificationList = listOf()
        imageUriList = listOf()
        relPostId = null
    }
    fun asNewPostWithImageUris(imageUris: List<String>) {
        textContent = ""
        searchPlaceAddressResult = null
        modificationList = listOf()
        imageUriList = imageUris
        relPostId = null
    }

    suspend fun uriToFile(context: Context, uri: Uri): File {
        val inputStream: InputStream? = context.contentResolver.openInputStream(uri)
        val tempFile = withContext(Dispatchers.IO) {
            File.createTempFile("temp", null, context.cacheDir)
        }
        inputStream?.use { input ->
            FileOutputStream(tempFile).use { output ->
                input.copyTo(output)
            }
        }
        return tempFile
    }

    fun validateMoment(): String? {
        if (imageUriList.isEmpty()) {
            return "Please select at least one image"
        }
        return null
    }
    suspend fun createMoment(context: Context, onUploadProgress: (Float) -> Unit) {
        val uploadImageList = emptyList<UploadImage>().toMutableList()
        var index = 0
        for (uri in imageUriList) {
            val cursor = context.contentResolver.query(Uri.parse(uri), null, null, null, null)
            cursor?.use {
                if (it.moveToFirst()) {
                    val displayName = it.getString(it.getColumnIndex("_display_name"))
                    val extension = displayName.substringAfterLast(".")
                    Log.d("NewPost", "File name: $displayName, extension: $extension")
                    // read as file
                    val file = uriToFile(context, Uri.parse(uri))
                    Log.d("NewPost", "File size: ${file.length()}")
                    uploadImageList += UploadImage(file, displayName, uri, extension)
                }
            }
            // 在上传过程中调用 onUploadProgress 更新进度
            onUploadProgress(((index / imageUriList.size).toFloat())) // progressValue 是当前上传进度，例如 0.5 表示 50%
            index += 1
        }
        momentService.createMoment(textContent, 1, uploadImageList, relPostId)
        // 刷新个人动态
        MyProfileViewModel.loadProfile()
        MomentViewModel.refreshPager()
    }

    suspend fun init() {
        relPostId?.let {
            val moment = momentService.getMomentById(it)
            relMoment = moment
        }
    }
    fun deleteImage(index: Int) {
        imageUriList = imageUriList.toMutableList().apply {
            removeAt(index)
        }
    }
}