package hanson.xyz.vpnhotspotmod

import android.bluetooth.BluetoothManager
import android.content.*
import android.graphics.drawable.Icon
import android.os.Build
import android.os.IBinder
import android.service.quicksettings.Tile
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import hanson.xyz.vpnhotspotmod.R
import hanson.xyz.vpnhotspotmod.TetheringService
import hanson.xyz.vpnhotspotmod.manage.BluetoothTethering
import hanson.xyz.vpnhotspotmod.net.TetherType
import hanson.xyz.vpnhotspotmod.net.TetheringManager
import hanson.xyz.vpnhotspotmod.net.TetheringManager.tetheredIfaces
import hanson.xyz.vpnhotspotmod.net.wifi.WifiApManager
import hanson.xyz.vpnhotspotmod.util.broadcastReceiver
import hanson.xyz.vpnhotspotmod.util.readableMessage
import hanson.xyz.vpnhotspotmod.util.stopAndUnbind
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import timber.log.Timber
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.net.ConnectivityManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import androidx.core.app.NotificationCompat

// added by hansonxyz

class MyBroadcastReceiver : BroadcastReceiver(), TetheringManager.StartTetheringCallback {

    private val handler = Handler(Looper.getMainLooper())

    /**
     * Called when tethering has been successfully started.
     */
//    override fun onTetheringStarted() {
//        // Retrieve the list of currently active tethering interfaces
//        val tetheredInterfaces = TetheringManager.tetheredIfaces
//
//        // Iterate over the interfaces and start the monitoring service for each
//        tetheredInterfaces.forEach { iface ->
//            Intent(App.app, TetheringService::class.java).apply {
//                action = TetheringService.ACTION_START_MONITORING
//                putExtra(TetheringService.EXTRA_INTERFACE, iface)
//                App.app.startForegroundService(this)
//            }
//        }
//    }

//
//    /**
//     * Called when starting tethering failed.
//     *
//     * @param error The error that caused the failure.
//     */
//    override fun onTetheringFailed(error: Int? = null) { }

//    private fun createNotificationChannel(context: Context) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            val name = "Tethering Notification"
//            val descriptionText = "Notifications for tethering status"
//            val importance = NotificationManager.IMPORTANCE_DEFAULT
//            val channel = NotificationChannel("TETHERING_STATUS", name, importance).apply {
//                description = descriptionText
//            }
//            val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//            notificationManager.createNotificationChannel(channel)
//        }
//    }
//
//    private fun showNotification(context: Context, title: String, message: String) {
//        createNotificationChannel(context)
//
//        val notificationBuilder = NotificationCompat.Builder(context, "TETHERING_STATUS")
//                .setSmallIcon(R.drawable.ic_launcher_foreground)
//                .setContentTitle(title)
//                .setContentText(message)
//                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
//
//        val notificationManager = ContextCompat.getSystemService(context, NotificationManager::class.java)
//        notificationManager?.notify(System.currentTimeMillis().toInt(), notificationBuilder.build())
//    }


    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            "BT_TETHER_START" -> {
                TetheringManager.startTethering(TetheringManager.TETHERING_BLUETOOTH, false, this)
            }
            "BT_TETHER_STOP" -> {
                TetheringManager.stopTethering(TetheringManager.TETHERING_BLUETOOTH)
            }
            "WIFI_TETHER_START" -> {
                val config = synchronized(BootReceiver) { BootReceiver.config }
                if (!(config == null || config.startables.isEmpty())) {
                    for (startable in config.startables.values) startable.start(App.app)
                }
                TetheringManager.startTethering(TetheringManager.TETHERING_WIFI, false, this)
//                showNotification(context, "Tethering Status", "Wi-Fi tethering started")
                    Intent(context, TetheringService::class.java).apply {
                        putExtra(TetheringService.EXTRA_ADD_INTERFACES, arrayOf("ap_br_wlan2"))
                        context.startForegroundService(this)
                    }
//                        Toast.makeText(context, "Monitoring service called for $iface", Toast.LENGTH_SHORT).show()
            }
            "WIFI_TETHER_STOP" -> {
                TetheringManager.stopTethering(TetheringManager.TETHERING_WIFI)
            }
            TetheringManager.ACTION_TETHER_STATE_CHANGED -> {
                val tetheredInterfaces = intent.getStringArrayListExtra(TetheringManager.EXTRA_ACTIVE_TETHER)
//                val message = if (tetheredInterfaces != null && tetheredInterfaces.isNotEmpty()) {
//                    "Tethering interfaces changed. Monitoring service called for ${tetheredInterfaces.joinToString(", ")}"
//                } else {
//                    "No active tethering interfaces found"
//                }
//                showNotification(context, "Tethering Status", message)
                if (tetheredInterfaces != null && tetheredInterfaces.isNotEmpty()) {
                    tetheredInterfaces.forEach { iface ->
                        Intent(context, TetheringService::class.java).apply {
                            putExtra(TetheringService.EXTRA_ADD_INTERFACES, arrayOf(iface))
                            context.startForegroundService(this)
                        }
//                        Toast.makeText(context, "Monitoring service called for $iface", Toast.LENGTH_SHORT).show()
                    }
                } else {
//                    Toast.makeText(context, "No active tethering interfaces found", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

}
