package com.recordatorios.app

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews

class TodayWidgetProvider : AppWidgetProvider() {

    override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
        for (appWidgetId in appWidgetIds) {
            updateWidget(context, appWidgetManager, appWidgetId)
        }
    }

    override fun onDeleted(context: Context, appWidgetIds: IntArray) {
        val prefs = context.getSharedPreferences(PREFS_WIDGET, Context.MODE_PRIVATE)
        for (id in appWidgetIds) {
            prefs.edit().remove("widget_${id}_show_time")
                .remove("widget_${id}_show_category")
                .remove("widget_${id}_max_items")
                .apply()
        }
    }

    companion object {
        const val PREFS_WIDGET = "widget_preferences"

        fun updateAllWidgets(context: Context) {
            val manager = AppWidgetManager.getInstance(context)
            val ids = manager.getAppWidgetIds(
                ComponentName(context, TodayWidgetProvider::class.java)
            )
            for (id in ids) {
                updateWidget(context, manager, id)
            }
        }

        private fun updateWidget(context: Context, manager: AppWidgetManager, appWidgetId: Int) {
            val prefs = context.getSharedPreferences(PREFS_WIDGET, Context.MODE_PRIVATE)
            val showTime = prefs.getBoolean("widget_${appWidgetId}_show_time", true)
            val showCategory = prefs.getBoolean("widget_${appWidgetId}_show_category", true)
            val maxItems = prefs.getInt("widget_${appWidgetId}_max_items", 10)

            val views = RemoteViews(context.packageName, R.layout.widget_today_info)
            views.setTextViewText(R.id.widgetItemCount, "")

            val intent = Intent(context, MainActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
            }
            val pi = PendingIntent.getActivity(
                context, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )
            views.setOnClickPendingIntent(R.id.widgetNoteList, pi)

            val serviceIntent = Intent(context, TodayWidgetService::class.java).apply {
                putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
                putExtra("show_time", showTime)
                putExtra("show_category", showCategory)
                putExtra("max_items", maxItems)
            }
            views.setRemoteAdapter(R.id.widgetNoteList, serviceIntent)
            views.setEmptyView(R.id.widgetNoteList, R.id.widgetEmptyView)

            manager.updateAppWidget(appWidgetId, views)
        }
    }
}
