package com.seven.ikar.kotlin.feature.transfer

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.pm.ServiceInfo
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.content.getSystemService
import androidx.work.ForegroundInfo
import com.seven.ikar.kotlin.R

object TransferForegroundNotification {
    const val LargeTransferThresholdBytes: Long = 8L * 1024L * 1024L
    private const val ChannelId = "ikar_transfers"

    fun createForegroundInfo(
        context: Context,
        groupId: String,
        title: String,
        message: String,
        progressPercent: Int?
    ): ForegroundInfo {
        ensureChannel(context)
        val notification = NotificationCompat.Builder(context, ChannelId)
            .setSmallIcon(R.drawable.ic_notification_transfer)
            .setContentTitle(title)
            .setContentText(message)
            .setOnlyAlertOnce(true)
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .apply {
                val progress = progressPercent?.coerceIn(0, 100)
                if (progress == null) {
                    setProgress(0, 0, true)
                } else {
                    setProgress(100, progress, false)
                }
            }
            .build()

        val notificationId = (groupId.hashCode() and Int.MAX_VALUE).coerceAtLeast(1)
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ForegroundInfo(notificationId, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
        } else {
            ForegroundInfo(notificationId, notification)
        }
    }

    private fun ensureChannel(context: Context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            return
        }

        val manager = context.getSystemService<NotificationManager>() ?: return
        if (manager.getNotificationChannel(ChannelId) != null) {
            return
        }

        manager.createNotificationChannel(
            NotificationChannel(
                ChannelId,
                "Передача файлов",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "Статус крупных загрузок и скачиваний"
                setShowBadge(false)
            }
        )
    }
}
