package com.example.absenkuv3


import android.app.AlertDialog
import android.app.Application
import android.app.ProgressDialog
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Matrix
import android.media.ExifInterface
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.absenku.sitepat.R
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

private const val FILENAME_FORMAT = "dd-MMM-yyyy"

val timeStamp: String = SimpleDateFormat(
    FILENAME_FORMAT,
    Locale.US
).format(System.currentTimeMillis())

fun createTempFile(context: Context): File {
    val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
    return File.createTempFile(timeStamp, ".jpg", storageDir)
}


fun createFile(application: Application): File {
    val mediaDir = application.externalMediaDirs.firstOrNull()?.let {
        File(it, application.resources.getString(R.string.app_name)).apply { mkdirs() }
    }

    val outputDirectory = if (
        mediaDir != null && mediaDir.exists()
    ) mediaDir else application.filesDir

    return File(outputDirectory, "$timeStamp.jpg")
}

fun rotateFile(file: File, isBackCamera: Boolean = false) {
    val matrix = Matrix()
    val bitmap = BitmapFactory.decodeFile(file.path)
    var rotation = 0f
    if (isBackCamera) {
        rotation = 90f

    } else {
        rotation = -90f
    }
    matrix.postRotate(rotation)
    if (!isBackCamera) {
        matrix.postScale(-1f, 1f, bitmap.width / 2f, bitmap.height / 2f)
    }
    val result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    result.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(file))
}
//fun resizeHeight(file: File, context: Context, progressDialog: ProgressDialog?) {
//    // Tampilkan indikator loading
//    progressDialog = ProgressDialog.show(context, "Compressing Image", "Please wait...", true)
//
//    val bitmap = BitmapFactory.decodeFile(file.path)
//    val compressedBitmap = Bitmap.createScaledBitmap(bitmap, DEFAULT_BUFFER_SIZE, 400, false)
//
//    // Kompresi gambar dan simpan ke file
//    try {
//        val outputStream = FileOutputStream(file)
//        compressedBitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream)
//        outputStream.flush()
//        outputStream.close()
//    } catch (e: IOException) {
//        e.printStackTrace()
//    }
//
//    // Sembunyikan indikator loading setelah kompresi selesai
//    progressDialog?.dismiss()
//}
//

interface ImageCompressionListener {
    fun onCompressionStarted()
    fun onCompressionFinished()
}
fun resizeHeight(file: File, newHeight: Int, listener: ImageCompressionListener) {
    // Beritahu listener bahwa proses kompresi telah dimulai
    val bitmap = BitmapFactory.decodeFile(file.path)
    listener.onCompressionStarted()

    val options = BitmapFactory.Options()
    options.inJustDecodeBounds = true
    BitmapFactory.decodeFile(file.path, options)

    // Mendapatkan lebar dan tinggi asli gambar
    val originalWidth = options.outWidth
    val originalHeight = options.outHeight

    // Menghitung skala faktor untuk mengubah tinggi sesuai dengan lebar asli
    val scaleFactor = originalWidth.toFloat() / originalHeight.toFloat()

//     Menyesuaikan tinggi gambar menjadi 400 piksel dengan tetap mempertahankan proporsi
    val newHeight = newHeight
    val newWidth = (newHeight * scaleFactor).toInt()
    val compressedBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false)

    // Kompresi gambar dan simpan ke file
    try {
        val outputStream = FileOutputStream(file)
        compressedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
        outputStream.flush()
        outputStream.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }

    // Beritahu listener bahwa proses kompresi telah selesai
    listener.onCompressionFinished()
}

fun resizeImage(file: File, newSize: Int, listener: ImageCompressionListener) {
    // Beritahu listener bahwa proses kompresi telah dimulai
    val bitmap = BitmapFactory.decodeFile(file.path)
    listener.onCompressionStarted()

    val options = BitmapFactory.Options()
    options.inJustDecodeBounds = true
    BitmapFactory.decodeFile(file.path, options)

    // Mendapatkan lebar dan tinggi asli gambar
    val originalWidth = options.outWidth
    val originalHeight = options.outHeight

    // Tentukan apakah gambar berorientasi potret atau landscape
    val isPortrait = originalHeight > originalWidth

    // Menyesuaikan dimensi gambar sesuai dengan orientasinya
    val adjustedWidth: Int
    val adjustedHeight: Int

    if (isPortrait) {
        // Jika potret, set lebar dan hitung tinggi
        adjustedWidth = newSize
        adjustedHeight = (adjustedWidth * (originalHeight.toFloat() / originalWidth.toFloat())).toInt()

    } else {
        // Jika landscape, set tinggi dan hitung lebar
        adjustedHeight = newSize
        adjustedWidth = (adjustedHeight * (originalWidth.toFloat() / originalHeight.toFloat())).toInt()
    }

    val compressedBitmap = Bitmap.createScaledBitmap(bitmap, adjustedWidth, adjustedHeight, false)

    // Kompresi gambar dan simpan ke file
    try {
        val outputStream = FileOutputStream(file)
        compressedBitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream)
        outputStream.flush()
        outputStream.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }

    // Beritahu listener bahwa proses kompresi telah selesai
    listener.onCompressionFinished()
}



fun customRotateFile(file: File, degree: Float) {
    val matrix = Matrix()
    val bitmap = BitmapFactory.decodeFile(file.path)
    matrix.postRotate(degree)
    val result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    result.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(file))

}

fun adjustImageOrientation(photoFile: File, isBackCamera: Boolean) {
    try {
        val exif = ExifInterface(photoFile.absolutePath)
        val orientation = exif.getAttributeInt(
            ExifInterface.TAG_ORIENTATION,
            ExifInterface.ORIENTATION_UNDEFINED
        )

        val matrix = Matrix()
//        when (orientation) {
//            ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
//            ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(270f)
////                ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(270f)
//            ExifInterface.ORIENTATION_NORMAL -> matrix.setRotate(90f)
////                else -> matrix.setRotate(90f)
//        }

//        when(orientation){
//            ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
//            ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f)
//            ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(270f)
////            ExifInterface.ORIENTATION_NORMAL -> matrix.setRotate(90f)
//            else -> matrix.setRotate(90f)
//        }


        Log.d("orientationz", orientation.toString())

        val originalBitmap = BitmapFactory.decodeFile(photoFile.absolutePath)
        var rotation = 0f
        if (isBackCamera) {
            rotation = 90f
        } else {
            rotation = when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> -90f
                ExifInterface.ORIENTATION_ROTATE_180 -> -180f
                ExifInterface.ORIENTATION_ROTATE_270 -> -270f
                else -> -90f
            }
        }
        matrix.postRotate(rotation)
        if (!isBackCamera) {
            matrix.postScale(-1f, 1f, originalBitmap.width / 2f, originalBitmap.height / 2f)
        }
        val result = Bitmap.createBitmap(
            originalBitmap,
            0,
            0,
            originalBitmap.width,
            originalBitmap.height,
            matrix,
            true
        )
        result.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(photoFile))
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

fun mirrorImage(file: File, flipHorizontally: Boolean, flipVertically: Boolean) {
    val bitmap = BitmapFactory.decodeFile(file.path)
    val matrix = Matrix()

    if (flipVertically && flipHorizontally)
        matrix.setScale(
            -1f,
            -1f
        )
    else if (flipVertically) {
        matrix.setScale(
            1f,
            -1f
        ) // Menetapkan skala -1 pada sumbu Y untuk memantulkan gambar secara vertikal
    } else if (flipHorizontally) {
        matrix.setScale(
            -1f,
            1f
        ) // Menetapkan skala -1 pada sumbu X untuk memantulkan gambar secara horizontal
    } else {
        matrix.setScale(1f, 1f) // Tanpa pemantulan jika tidak perlu
    }
    val result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    result.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(file))
}

fun getExifOrientation(path: String): Int {
    val exif = ExifInterface(path)
    val orientation =
        exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)

    return when (orientation) {
        ExifInterface.ORIENTATION_ROTATE_90 -> 90
        ExifInterface.ORIENTATION_ROTATE_180 -> 180
        ExifInterface.ORIENTATION_ROTATE_270 -> 270
        else -> 0
    }
}

fun showAlertDialog(context: Context, message: String,language: String? = "id") {
    val builder = AlertDialog.Builder(
        context,
        R.style.CustomAlertDialog
    ).create()

    val view = LayoutInflater.from(context).inflate(R.layout.customviewdialog, null)
    val titleTextView = view.findViewById<TextView>(R.id.dialogTitle_textView)
    val messageTextView = view.findViewById<TextView>(R.id.dialogMessage_textView)
    val closeButton = view.findViewById<ImageView>(R.id.imageView_close)
    val dismissButton = view.findViewById<TextView>(R.id.dialogDismiss_button)
    val closeTextView = view.findViewById<TextView>(R.id.dialogDismiss_button)

    titleTextView.visibility = View.VISIBLE
    messageTextView.visibility = View.VISIBLE
    closeButton.visibility = View.VISIBLE

    titleTextView.setTextColor(Color.parseColor("#FF0000"))
    titleTextView.text = if (language == "id") "Gagal" else "Failed"
    messageTextView.text = message
    closeTextView.text = if (language == "id") "Tutup" else "Close"

    builder.setView(view)
    dismissButton.setOnClickListener {
        builder.dismiss()
    }
    builder.setCanceledOnTouchOutside(false)
    builder.show()
}


class LoadingHelper(private val context: Context) {
    private var loadingDialog: ProgressDialog? = null
    fun showLoadingMessage() {
        // Pastikan dialog hanya dibuat jika belum ada
        if (loadingDialog == null) {
            loadingDialog = ProgressDialog(context)
            loadingDialog?.setMessage("Loading...") // Pesan yang ingin ditampilkan
            loadingDialog?.setCancelable(false)
        }
        // Tampilkan dialog
        loadingDialog?.show()
    }

    fun hideLoadingMessage() {
        // Pastikan dialog tidak null sebelum menyembunyikannya
        loadingDialog?.dismiss()
        loadingDialog = null
    }
}


