package com.syaroful.agrilinkvocpro.plant_disease_detection_feature.presentation.camera

import android.graphics.Bitmap
import android.util.Log
import androidx.camera.view.LifecycleCameraController
import androidx.lifecycle.ViewModel
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.core.extention.cropToSquare
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.core.extention.resize
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.repository.CameraRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.util.concurrent.Executor

private const val TAG = "CameraViewModel"

class CameraViewModel(
    private val cameraRepository: CameraRepository,
) : ViewModel() {


    private val _uiState = MutableStateFlow(CameraUIState())
    val uiState: StateFlow<CameraUIState> = _uiState

    private val _bitmap = MutableStateFlow<Bitmap?>(null)
    val bitmap: StateFlow<Bitmap?> = _bitmap


    fun takePicture(
        controller: LifecycleCameraController,
        executor: Executor,
        onFinish: () -> Unit
    ) {
        Log.d(TAG, "takePicture() called")
        _uiState.value = _uiState.value.copy(isLoading = true)

        cameraRepository.takePicture(controller, executor) { bitmap ->
            Log.d(TAG, "Picture taken, updating state")
            val croppedImage = cropToSquare(bitmap)
            _bitmap.value = croppedImage.resize()
//            croppedImage.let {
//                diagnosisViewModel.analyzePlant(bitmap = it, prompt = prompt)
//                Log.d(TAG, "analyzePlant() called")
//            }
            _uiState.value = _uiState.value.copy(isLoading = false)

            onFinish()
        }
    }
}