package eu.mhsl.marianum.mobile.client

import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.os.Bundle
import eu.mhsl.marianum.mobile.client.widgets.WidgetRefreshRequester
import eu.mhsl.marianum.mobile.client.widgets.WidgetRenderer

/**
 * Lives at the package root (not under `widgets/`) because the home_widget
 * Flutter plugin resolves the receiver class as `<app-package>.<androidName>`.
 */
class TimetableDayWidget : AppWidgetProvider() {
    override fun onEnabled(context: Context) {
        // First widget of this kind placed → fetch fresh data right away.
        WidgetRefreshRequester.enqueueOneOffRefresh(context)
    }

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray,
    ) {
        for (id in appWidgetIds) {
            val options = appWidgetManager.getAppWidgetOptions(id)
            val views = WidgetRenderer.buildDay(context, context.packageName, options)
            appWidgetManager.updateAppWidget(id, views)
        }
    }

    override fun onAppWidgetOptionsChanged(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetId: Int,
        newOptions: Bundle,
    ) {
        // Re-render on resize, otherwise the tiles stay at install-time size
        // and either clip or leave dead space.
        val views = WidgetRenderer.buildDay(context, context.packageName, newOptions)
        appWidgetManager.updateAppWidget(appWidgetId, views)
    }
}
