package com.cpm.india.cameraai.preview
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.cpm.india.cameraai.databinding.ActivityPreviewBinding
import com.cpm.india.cameraai.utils.GetProperImageRotation
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class PreviewActivity : AppCompatActivity() {
    private lateinit var cameraExecutor: ExecutorService
    private lateinit var binding: ActivityPreviewBinding
    private var photoUri: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPreviewBinding.inflate(layoutInflater)
        setContentView(binding.root)
        cameraExecutor = Executors.newSingleThreadExecutor()
        photoUri = intent.getStringExtra("photoUri")
        val photoFile = photoUri?.let { File(it) }
        if (photoUri != null) {
            Log.d("uridata", photoUri!!)
        }

        val rotatedImageFile = GetProperImageRotation.getRotatedImageFile(photoFile, photoUri, this)
        binding.capturedImageView.setImageBitmap(BitmapFactory.decodeFile(rotatedImageFile?.absolutePath))
        binding.retakeLL.setOnClickListener {
            finish() // Go back to the camera activity
        }

        binding.cancelLL.setOnClickListener {
            deleteImageFile(photoFile!!.absolutePath)
            finish() // Go back to the camera activity
        }

        binding.saveLL.setOnClickListener {
            val intent = Intent()
            intent.putExtra("filePath", photoUri!!)
            setResult(RESULT_OK, intent)
            finish()
        }
    }

    private fun deleteImageFile(filePath: String): Boolean {
        val file = File(filePath)
        return if (file.exists()) {
            val isDeleted = file.delete()
            if (isDeleted) {
                Log.d("FileDeletion", "File deleted successfully: $filePath")
            } else {
                Log.e("FileDeletion", "File deletion failed: $filePath")
            }
            isDeleted
        } else {
            Log.e("FileDeletion", "File does not exist: $filePath")
            false
        }
    }

    // Ensure to shut down the executor
    override fun onDestroy() {
        super.onDestroy()
        cameraExecutor.shutdown()
    }
}