package com.example.absenkuv3.camerax

import android.app.ProgressDialog
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.WindowInsets
import android.view.WindowManager
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import com.absenku.sitepat.R

import com.example.absenkuv3.*
import com.example.absenkuv3.broadcast.EventChannelHandler


class CameraxActivity : AppCompatActivity() {
    private val tag = "CameraxActivity"
    private var cameraSelector: CameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
    // private var cameraSelector: CameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
    private var imageCapture: ImageCapture? = null
    // Membuat instance CameraOrientationListener
//    private var progressDialog: ProgressDialog? = null



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camerax)
        val kameraBelakang = intent.getBooleanExtra(EXTRA_KAMERA_BELAKANG, false)
        
        Log.d(tag, "Nilai kameraBelakang: $kameraBelakang")

        val headerText = intent.getStringExtra(EXTRA_HEADER_TEXT) ?: "Judul Default"
        Log.d(tag, "Header text received: $headerText")

        val headerTextView = findViewById<TextView>(R.id.headerText)
        headerTextView.post {
            headerTextView.text = headerText
        }

        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.title = headerText
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowHomeEnabled(true)
        Log.d(tag, "Toolbar title updated: ${supportActionBar?.title}")

        toolbar.setNavigationOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        if (!kameraBelakang) {
            findViewById<ImageButton>(R.id.switchCamera).visibility = ImageButton.GONE
        }
        findViewById<ImageButton>(R.id.captureImage).setOnClickListener {
            takePicture()
        }
        findViewById<ImageButton>(R.id.switchCamera).setOnClickListener {
            cameraSelector =
                if (cameraSelector.equals(CameraSelector.DEFAULT_FRONT_CAMERA)) CameraSelector.DEFAULT_BACK_CAMERA
                else CameraSelector.DEFAULT_FRONT_CAMERA
            startCamera()
        }

    }

    public override fun onResume() {
        super.onResume()
        hideSystemUI()
        startCamera()
    }

    private fun takePicture() {
        val eventChannelHandler = EventChannelHandler(context = applicationContext)
        val imageCapture = imageCapture ?: return
        val photoFile = createTempFile(application)
        val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
        imageCapture.targetRotation = windowManager.defaultDisplay.rotation
        val progressDialog = ProgressDialog.show(this, "Proses", "Harap menunggu...", true)

        imageCapture.takePicture(
            outputOptions,
            ContextCompat.getMainExecutor(this),
            object : ImageCapture.OnImageSavedCallback {
                override fun onError(exc: ImageCaptureException) {
                    Toast.makeText(
                        this@CameraxActivity,
                        "Gagal mengambil gambar.",
                        Toast.LENGTH_SHORT
                    ).show()
                }

                override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                    // Log.d("TAG", "onImageSaved: ${photoFile.absolutePath}")
                    val photoFilePath = photoFile.absolutePath
                    val orientation = getExifOrientation(photoFilePath)
                    // Log.d("ori2", "ori2 ${orientation}")
                    if (cameraSelector == CameraSelector.DEFAULT_FRONT_CAMERA) {
                        when (orientation) {
                            270 -> {
                                rotateFile(photoFile)
                            }
                            180 -> {
                                mirrorImage(
                                    photoFile,
                                    flipHorizontally = false,
                                    flipVertically = true
                                )
                            }
                            90 -> {
                                customRotateFile(photoFile, 90f)
                            }
                            0 -> {
                                mirrorImage(
                                    photoFile,
                                    flipHorizontally = true,
                                    flipVertically = false
                                )
                            }
                        }
                        // Log.d("masukflip", "masuk ${cameraSelector}")
                    } else {
                        when (orientation) {
                            270 -> {
                                rotateFile(photoFile)
                            }
                            180 -> {
                                mirrorImage(
                                    photoFile,
                                    flipHorizontally = true,
                                    flipVertically = true
                                )
                            }
                            90 -> {
                                customRotateFile(photoFile, 90f)
                            }
                            0 -> {
                                customRotateFile(photoFile, 0f)
                            }
                        }
                        // Log.d("masukflip", "ga")
                    }
                    val data = HashMap<String, String>()
                    data["foto"] = photoFile.absolutePath
                    data["matrix"] = "[]"
                    resizeImage(photoFile,500, object : ImageCompressionListener {
                        override fun onCompressionStarted() {
                        }

                        override fun onCompressionFinished() {
                            eventChannelHandler.onReportCameraClicked(
                                applicationContext,
                                tag,
                                data
                            )
                            finish()
                            progressDialog.dismiss()
                        }
                    })
                }
            }
        )
    }


    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this@CameraxActivity)
        cameraProviderFuture.addListener({
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .build()
                .also {
                    it.setSurfaceProvider(findViewById<PreviewView>(R.id.viewFinder).surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(
                    this,
                    cameraSelector,
                    preview,
                    imageCapture
                )
            } catch (exc: Exception) {
                Toast.makeText(
                    this@CameraxActivity,
                    "Gagal memunculkan kamera.",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }, ContextCompat.getMainExecutor(this))
    }

    private fun hideSystemUI() {
        @Suppress("DEPRECATION")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.insetsController?.hide(WindowInsets.Type.statusBars())
        } else {
            window.setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
            )
        }
        supportActionBar?.hide()
    }


    companion object {

        const val EXTRA_HEADER_TEXT = "extra_header_text"
        const val EXTRA_KAMERA_BELAKANG = "extra_kamera_belakang"

    }
}