package bou.amine.apps.readerforselfossv2.android.background

import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.PRIORITY_DEFAULT
import androidx.core.app.NotificationCompat.PRIORITY_LOW
import androidx.work.Worker
import androidx.work.WorkerParameters
import bou.amine.apps.readerforselfossv2.android.MainActivity
import bou.amine.apps.readerforselfossv2.android.MyApp
import bou.amine.apps.readerforselfossv2.android.R
import bou.amine.apps.readerforselfossv2.android.model.preloadImages
import bou.amine.apps.readerforselfossv2.android.utils.network.isNetworkAccessible
import bou.amine.apps.readerforselfossv2.model.SelfossModel
import bou.amine.apps.readerforselfossv2.repository.Repository
import bou.amine.apps.readerforselfossv2.service.AppSettingsService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.kodein.di.DIAware
import org.kodein.di.instance
import java.util.*
import kotlin.concurrent.schedule

class LoadingWorker(val context: Context, params: WorkerParameters) : Worker(context, params), DIAware {

    override val di by lazy { (applicationContext as MyApp).di }
    private val repository : Repository by instance()
    private val appSettingsService : AppSettingsService by instance()

override fun doWork(): Result {
    if (appSettingsService.isPeriodicRefreshEnabled() && isNetworkAccessible(context)) {

        CoroutineScope(Dispatchers.IO).launch {
            val notificationManager =
                applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            val notification =
                NotificationCompat.Builder(applicationContext, AppSettingsService.syncChannelId)
                    .setContentTitle(context.getString(R.string.loading_notification_title))
                    .setContentText(context.getString(R.string.loading_notification_text))
                    .setOngoing(true)
                    .setPriority(PRIORITY_LOW)
                    .setChannelId(AppSettingsService.syncChannelId)
                    .setSmallIcon(R.drawable.ic_stat_cloud_download_black_24dp)

            notificationManager.notify(1, notification.build())

            repository.handleDBActions()

            if (appSettingsService.isNotifyNewItemsEnabled()) {
                launch {
                    handleNewItemsNotification(repository.tryToCacheItemsAndGetNewOnes(), notificationManager)
                }
            }
        }
    }
    return Result.success()
}

    private fun handleNewItemsNotification(
        newItems: List<SelfossModel.Item>?,
        notificationManager: NotificationManager
    ) {
        CoroutineScope(Dispatchers.IO).launch {
                val apiItems = newItems.orEmpty()


                val newSize = apiItems.filter { it.unread }.size
                if (newSize > 0) {

                    val intent = Intent(context, MainActivity::class.java).apply {
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                    }
                    val pflags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        PendingIntent.FLAG_IMMUTABLE
                    } else {
                        0
                    }
                    val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, pflags)

                    val newItemsNotification =
                        NotificationCompat.Builder(applicationContext, AppSettingsService.newItemsChannelId)
                            .setContentTitle(context.getString(R.string.new_items_notification_title))
                            .setContentText(
                                context.getString(
                                    R.string.new_items_notification_text,
                                    newSize
                                )
                            )
                            .setPriority(PRIORITY_DEFAULT)
                            .setChannelId(AppSettingsService.newItemsChannelId)
                            .setContentIntent(pendingIntent)
                            .setAutoCancel(true)
                            .setSmallIcon(R.drawable.ic_tab_fiber_new_black_24dp)

                    Timer("", false).schedule(4000) {
                        notificationManager.notify(2, newItemsNotification.build())
                    }
                }
                apiItems.map { it.preloadImages(context) }
            Timer("", false).schedule(4000) {
                notificationManager.cancel(1)
            }
        }
    }
}