package com.example.hmg_qline.hmg_qline


import android.app.AlarmManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.lifecycle.LifecycleService
import android.app.ActivityManager

class BootForegroundService : LifecycleService() {
    override fun onCreate() {
        super.onCreate()
        startForegroundService()
        schedulePeriodicCheck()
    }

    private fun startForegroundService() {
        val channelId = "boot_service_channel"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "Boot Service Channel",
                NotificationManager.IMPORTANCE_HIGH
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager?.createNotificationChannel(channel)
        }

        val notification: Notification = NotificationCompat.Builder(this, channelId)
            .setContentTitle("QLine App")
            .setContentText("Monitoring QLine activity...")
            .setSmallIcon(R.mipmap.ic_launcher)
            .build()

        startForeground(1, notification)

        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningProcesses = activityManager.runningAppProcesses

        var isAppInForeground = false
        for (process in runningProcesses) {
            if (process.processName == packageName &&
                process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
            ) {
                isAppInForeground = true
                break
            }
        }

        if (!isAppInForeground) {
            Log.d("BootForegroundService", "App is NOT in foreground — launching MainActivity.")
            val intent = Intent(this, MainActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            }
            startActivity(intent)
        } else {
            Log.d("BootForegroundService", "App is already in foreground.")
        }

        stopSelf() // Stop the service after check
    }


    private fun schedulePeriodicCheck() {
        val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(this, BootForegroundService::class.java)
        val pendingIntent = PendingIntent.getService(
            this,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        // Repeat every 1 minute
        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + 60 * 1000,
            60 * 1000,
            pendingIntent
        )

    }

    private fun bringAppToFrontIfNotVisible() {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningProcesses = activityManager.runningAppProcesses

        val isAppInForeground = runningProcesses.any {
            it.processName == packageName && it.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
        }

        if (!isAppInForeground) {
            Log.d("BootForegroundService", "App is not in foreground, launching MainActivity")
            val intent = Intent(this, MainActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            startActivity(intent)
        } else {
            Log.d("BootForegroundService", "App is already in foreground")
        }
    }
}