package it.danieleverducci.openweddingapp.utils

import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.android.volley.VolleyError
import it.danieleverducci.openweddingapp.Config
import it.danieleverducci.openweddingapp.entities.NtfyMessage
import it.danieleverducci.openweddingapp.networking.NtfySubscriptionNet

class NotificationWorker(appContext: Context, workerParams: WorkerParameters)
    : Worker(appContext, workerParams) {

    companion object {
        val TAG = "NotificationWorker"
    }

    val notificationUtils: NotificationUtils
    val ntfySubscriptionNet: NtfySubscriptionNet

    init {
        notificationUtils = NotificationUtils(applicationContext)
        ntfySubscriptionNet = NtfySubscriptionNet(applicationContext)
    }

    override fun doWork(): Result {
        Log.d(TAG, "Checking for notifications")

        // Check for notifications
        checkNtfyTopic(Config.NTFY_GENERAL_TOPIC)
        val presence = SharedPreferencesManager.loadPresence(applicationContext)
        if (presence == null) {
            Log.d(TAG, "Checking notif for DNR")
            checkNtfyTopic(Config.NTFY_DNR_TOPIC)
        } else if (presence.willBePresent) {
            Log.d(TAG, "Checking notif for YES")
            checkNtfyTopic(Config.NTFY_WILLBETHERE_TOPIC)
        } else {
            Log.d(TAG, "Checking notif for NO")
            checkNtfyTopic(Config.NTFY_WILLNOTBETHERE_TOPIC)
        }

        SharedPreferencesManager.saveLocalSettingsLastNotificationCheck(applicationContext, System.currentTimeMillis())
        return Result.success()
    }

    private fun checkNtfyTopic(topic: String) {
        val ntfySubscriptionNet = NtfySubscriptionNet(applicationContext)
        val lastCheckInSeconds = SharedPreferencesManager.loadLocalSettingsLastNotificationCheck(applicationContext) / 1000
        ntfySubscriptionNet.getItems("${Config.NTFY_BASE_URL}${topic}/json?poll=1", object: NtfySubscriptionNet.OnItemsObtainedListener {

            override fun OnItemsObtained(items: List<NtfyMessage>) {
                val nu = NotificationUtils(applicationContext)
                for (ntfyItem in items) {
                    if (ntfyItem.time > lastCheckInSeconds)
                        nu.createNotification(ntfyItem.message)
                }
            }

            override fun OnError(error: VolleyError) {
                Log.e(TAG, "Unable to obtain notifications for topic ${topic}: ${error}")
            }
        })
    }
}
