package com.absenku.sitepat

import android.content.Intent
import androidx.annotation.NonNull
import com.example.absenkuv3.broadcast.EventChannelHandler
import com.example.absenkuv3.camerax.CameraxActivity
import com.example.absenkuv3.facex.FaceCameraXActivity
import com.example.absenkuv3.security.SecurityChecker
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.media.AudioAttributes
import android.net.Uri
import android.content.ContentResolver
import android.util.Log
import android.media.MediaPlayer
import android.location.LocationManager
import android.location.Location


class MainActivity: FlutterActivity() {
    private val tag = "MainActivity"
    private lateinit var securityChecker: SecurityChecker

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        createNotificationChannel(this)
    }
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        securityChecker = SecurityChecker(this)

        val eventChannelHandler = EventChannelHandler(context = applicationContext)
        eventChannelHandler.startListening(flutterEngine, CHARGING_CHANNEL, tag)

        // Security channel
        MethodChannel(flutterEngine.dartExecutor, "com.example.absenkuv3/security")
            .setMethodCallHandler { call, result ->
                when (call.method) {
                    "isDeveloperModeEnabled" -> {
                        val isDevMode = securityChecker.isDeveloperModeEnabled(context)
                        result.success(isDevMode)
                    }
                    else -> result.notImplemented()
                }
            }

        // Cek Mock Location

        MethodChannel(flutterEngine.dartExecutor, "com.example.absenkuv3/location")
            .setMethodCallHandler { call, result ->
                when (call.method) {
                    "isLocationFake" -> {
                        val isFake = isLocationFromMockProvider(this)
                        result.success(isFake)
                    }
                    else -> result.notImplemented()
                }
            }
        // Source checker
        MethodChannel(flutterEngine.dartExecutor, "com.example.absenkuv3")
            .setMethodCallHandler { call, result ->
                when (call.method) {
                    "startCekSource" -> {
                        val installer =
                            context.packageManager.getInstallerPackageName(context.packageName)
                        val installer2 = installer ?: "unknown"
                        result.success(installer2)
                    }
                    else -> result.notImplemented()
                }
            }

        // Camerax + Face
        MethodChannel(flutterEngine.dartExecutor, CAMERAX_CHANELL)
            .setMethodCallHandler { call, result ->
                when (call.method) {
                    "startCameraXActivity" -> {
                        val kameraBelakang = call.argument<Boolean>("kameraBelakang")
                        val headerText = call.argument<String>("header_text")
                        Log.d(tag, "Nilai kameraBelakang1: $kameraBelakang")
                        Log.d(tag, "Header text received main: $headerText")
                        val intent = Intent(this, CameraxActivity::class.java)
                        intent.putExtra(CameraxActivity.EXTRA_KAMERA_BELAKANG, kameraBelakang)
                        intent.putExtra(CameraxActivity.EXTRA_HEADER_TEXT, headerText)
                        startActivity(intent)
                    }

                    "startFaceCameraXActivity" -> {
                        val matrix = call.argument<String>("matrix")
                        val register = call.argument<Boolean>("register")
                        val peringatan = call.argument<String>("peringatan")
                        val language = call.argument<String>("language")
                        val cosineThreshold = call.argument<Double>("cosineThreshold")!!.toDouble()
                        val l2Threshold = call.argument<Double>("l2Threshold")!!.toDouble()
                        val headerText = call.argument<String>("header_text")

                        val intent = Intent(this, FaceCameraXActivity::class.java)
                        intent.putExtra(FaceCameraXActivity.EXTRA_MATRIX, matrix)
                        intent.putExtra(FaceCameraXActivity.EXTRA_REGISTER, register)
                        intent.putExtra(FaceCameraXActivity.EXTRA_PERINGATAN, peringatan)
                        intent.putExtra(FaceCameraXActivity.EXTRA_COSINETHRESHOLD, cosineThreshold)
                        intent.putExtra(FaceCameraXActivity.EXTRA_L2THRESHOLD, l2Threshold)
                        intent.putExtra(FaceCameraXActivity.EXTRA_LANGUAGE, language)
                        intent.putExtra(FaceCameraXActivity.EXTRA_HEADER_TEXT, headerText)
                        startActivity(intent)
                    }

                    else -> result.notImplemented()
                }
            }
    }
    companion object {
        private const val CAMERAX_CHANELL = "absenku/camerax"
        private const val CHARGING_CHANNEL = "absenku/camerax/report"

    }
    data class NotificationChannelData(val id: String, val name: String, val soundResId: Int)
    private fun createNotificationChannel(context: Context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channels = listOf(
            NotificationChannelData("channel_id_1", "absensi", R.raw.absenku),
            NotificationChannelData("channel_id_2", "general", R.raw.access),
            NotificationChannelData("channel_id_3", "emergency", R.raw.emergency)
        )

        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            channels.forEach { channelData ->
                val soundUri = Uri.parse("android.resource://${context.packageName}/${channelData.soundResId}")
                val audioAttributes = AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build()
                val vibrationPattern = LongArray(60) { index ->
                    if (index % 2 == 0) 500L else 500L
                    }
                val channel = NotificationChannel(channelData.id, channelData.name, NotificationManager.IMPORTANCE_HIGH).apply {
                    description = channelData.name
                    setSound(soundUri, audioAttributes)
                    enableVibration(true)
                    setBypassDnd(true)
                    this.vibrationPattern = vibrationPattern
                }
                notificationManager.createNotificationChannel(channel)
            }
        }
        }
//    private fun isLocationFromMockProvider(context: Context): Boolean {
//        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
//        val providers = locationManager.getProviders(true)
//
//        for (provider in providers) {
//            try {
//                val location = locationManager.getLastKnownLocation(provider)
//                if (location != null) {
//                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
//                        return location.isMock
//                    } else {
//                        return location.isFromMockProvider
//                    }
//                }
//            } catch (e: SecurityException) {
//                return false
//            }
//        }
//        return false
//    }
private fun isLocationFromMockProvider(context: Context): Boolean {
    val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager

    return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
        try {
            // Check if any provider has mock location enabled
            val providers = locationManager.allProviders
            for (provider in providers) {
                val location: Location? = locationManager.getLastKnownLocation(provider)
                location?.let {
                    if (it.isFromMockProvider) {
                        return true
                    }
                }
            }
            false
        } catch (e: Exception) {
            false
        }
    } else {
        // For older versions
        android.provider.Settings.Secure.getInt(
            context.contentResolver,
            android.provider.Settings.Secure.ALLOW_MOCK_LOCATION, 0
        ) != 0
    }
}
}
