package com.example.godeye.services

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.example.godeye.R
import com.example.godeye.managers.ConnectionManager
import com.example.godeye.managers.AutoApprovalManager
import com.example.godeye.utils.PreferenceManager
import kotlinx.coroutines.*

/**
 * Фоновый сервис для поддержания подключения к серверу
 */
class ConnectionService : Service() {

    companion object {
        private const val TAG = "ConnectionService"
        private const val NOTIFICATION_ID = 1000
        private const val CHANNEL_ID = "connection_service"

        const val ACTION_START = "action_start"
        const val ACTION_STOP = "action_stop"
        const val ACTION_CONNECT = "action_connect"
        const val ACTION_DISCONNECT = "action_disconnect"
    }

    private lateinit var connectionManager: ConnectionManager
    private lateinit var autoApprovalManager: AutoApprovalManager
    private lateinit var preferenceManager: PreferenceManager
    private lateinit var notificationManager: NotificationManager

    private val serviceScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private var statusUpdateJob: Job? = null

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "Service created")

        preferenceManager = PreferenceManager(this)
        connectionManager = ConnectionManager(this, preferenceManager)
        autoApprovalManager = AutoApprovalManager(this, preferenceManager, connectionManager)
        notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        createNotificationChannel()
        startMonitoring()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when (intent?.action) {
            ACTION_START -> {
                Log.d(TAG, "Starting foreground service")
                startForeground(NOTIFICATION_ID, createNotification("Запуск сервиса..."))

                // Автоподключение если включено
                if (preferenceManager.getAutoConnect()) {
                    connectionManager.connect()
                }
            }
            ACTION_STOP -> {
                Log.d(TAG, "Stopping service")
                stopSelf()
            }
            ACTION_CONNECT -> {
                Log.d(TAG, "Connect command received")
                connectionManager.connect()
            }
            ACTION_DISCONNECT -> {
                Log.d(TAG, "Disconnect command received")
                connectionManager.disconnect()
            }
        }

        return START_STICKY // Перезапускать сервис при остановке системой
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "Service destroyed")

        statusUpdateJob?.cancel()
        serviceScope.cancel()
        connectionManager.cleanup()
        autoApprovalManager.cleanup()
    }

    /**
     * Создание канала уведомлений
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "Подключение GodEye",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "Статус подключения к серверу GodEye"
                setShowBadge(false)
                enableLights(false)
                enableVibration(false)
            }
            notificationManager.createNotificationChannel(channel)
        }
    }

    /**
     * Создание уведомления
     */
    private fun createNotification(content: String): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("GodEye Signal Center")
            .setContentText(content)
            .setSmallIcon(R.drawable.ic_camera_active)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setOngoing(true)
            .setShowWhen(false)
            .build()
    }

    /**
     * Мониторинг состояния подключения
     */
    private fun startMonitoring() {
        statusUpdateJob = serviceScope.launch {
            connectionManager.connectionState.collect { state ->
                val statusText = when (state) {
                    ConnectionManager.ConnectionState.CONNECTED -> "Подключено к серверу"
                    ConnectionManager.ConnectionState.CONNECTING -> "Подключение..."
                    ConnectionManager.ConnectionState.ERROR -> "Ошибка подключения"
                    ConnectionManager.ConnectionState.DISCONNECTED -> "Отключен"
                    ConnectionManager.ConnectionState.RECONNECTING -> "Переподключение..."
                }

                // Обновляем уведомление
                val notification = createNotification(statusText)
                notificationManager.notify(NOTIFICATION_ID, notification)

                Log.d(TAG, "Connection state changed: $statusText")
            }
        }
    }
}
