/*
 * Copyright © Harsh Shandilya.
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 */
package dev.msfjarvis.claw.android

import android.app.Application
import android.os.Build
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import dev.msfjarvis.claw.android.injection.AppGraph
import dev.msfjarvis.claw.android.work.GeneratedWidgetPreviewUpdateWorker
import dev.msfjarvis.claw.android.work.SavedPostUpdaterWorker
import dev.msfjarvis.claw.android.work.TagExpirationCleanupWorker
import dev.zacsweers.metro.createGraphFactory
import dev.zacsweers.metrox.android.MetroAppComponentProviders
import dev.zacsweers.metrox.android.MetroApplication
import java.util.concurrent.TimeUnit

class ClawApplication : Application(), MetroApplication {

  val appGraph by lazy { createGraphFactory<AppGraph.Factory>().create(this) }

  override val appComponentProviders: MetroAppComponentProviders
    get() = appGraph

  override fun onCreate() {
    super.onCreate()
    appGraph.plugins.forEach { plugin -> plugin.apply(this) }
    val postUpdateWorkRequest =
      PeriodicWorkRequestBuilder<SavedPostUpdaterWorker>(24, TimeUnit.HOURS)
        .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
        .build()
    appGraph.workManager.enqueueUniquePeriodicWork(
      uniqueWorkName = "updateSavedPosts",
      existingPeriodicWorkPolicy = ExistingPeriodicWorkPolicy.KEEP,
      request = postUpdateWorkRequest,
    )
    val tagCleanupWorkRequest =
      PeriodicWorkRequestBuilder<TagExpirationCleanupWorker>(24, TimeUnit.HOURS).build()
    appGraph.workManager.enqueueUniquePeriodicWork(
      uniqueWorkName = "cleanupExpiredTags",
      existingPeriodicWorkPolicy = ExistingPeriodicWorkPolicy.KEEP,
      request = tagCleanupWorkRequest,
    )
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
      GeneratedWidgetPreviewUpdateWorker.enqueue(appGraph.workManager)
    }
  }
}
