package com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.repository

import android.graphics.Bitmap
import android.graphics.Matrix
import android.util.Log
import androidx.camera.core.ImageCapture.OnImageCapturedCallback
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.ImageProxy
import androidx.camera.view.LifecycleCameraController
import java.util.concurrent.Executor

class CameraRepositoryImpl : CameraRepository {

    override fun takePicture(
        controller: LifecycleCameraController,
        executor: Executor,
        onPictureTaken: (Bitmap) -> Unit
    ) {
        Log.d("CameraRepository", "Starting takePicture")

        controller.takePicture(
            executor,
            object : OnImageCapturedCallback() {
                override fun onCaptureSuccess(image: ImageProxy) {
                    Log.d("CameraRepository", "Capture success")

                    try {
                        val rotationDegrees = image.imageInfo.rotationDegrees
                        Log.d("CameraRepository", "Rotation: $rotationDegrees")

                        val matrix = Matrix().apply {
                            postRotate(rotationDegrees.toFloat())
                        }

                        val originalBitmap = image.toBitmap()
                        Log.d("CameraRepository", "Original bitmap size: ${originalBitmap.width} x ${originalBitmap.height}")

                        val rotatedBitmap = Bitmap.createBitmap(
                            originalBitmap,
                            0, 0,
                            image.width,
                            image.height,
                            matrix,
                            true
                        )

                        Log.d("CameraRepository", "Rotated bitmap size: ${rotatedBitmap.width} x ${rotatedBitmap.height}")

                        onPictureTaken(rotatedBitmap)

                    } catch (e: Exception) {
                        Log.e("CameraRepository", "Error while processing image: ${e.message}", e)
                    } finally {
                        image.close()
                    }
                }

                override fun onError(exception: ImageCaptureException) {
                    Log.e("CameraRepository", "Couldn't take photo: ${exception.message}", exception)
                }
            }
        )
    }
}