package tk.zwander.lockscreenwidgets.activities.add

import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.compose.ui.unit.IntSize
import tk.zwander.common.activities.add.AddWidgetActivity
import tk.zwander.common.data.WidgetData
import tk.zwander.common.host.WidgetHostCompat
import tk.zwander.common.util.prefManager

class AddWidgetStackWidgetActivity : AddWidgetActivity() {
    private val widgetId by lazy {
        intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, WidgetHostCompat.INVALID_WIDGET_ID)
    }

    override val showShortcuts: Boolean = false
    override val showWidgetStackWidget: Boolean = false
    override val gridSize: IntSize = IntSize(1, 1)
    override val colCount: Int = 1
    override val rowCount: Int = 1
    override val width: Float = 100f
    override val height: Float = 100f

    override var currentWidgets: Set<WidgetData>
        get() = prefManager.widgetStackWidgets[widgetId] ?: LinkedHashSet()
        // Saving happens in the configuration Activity when hitting Apply.
        set(_) {}

    override fun onCreate(savedInstanceState: Bundle?) {
        if (widgetId == WidgetHostCompat.INVALID_WIDGET_ID) {
            finish()
        }

        super.onCreate(savedInstanceState)
    }

    override fun onItemSuccessfullyAdded(data: WidgetData) {
        setResult(
            RESULT_OK,
            Intent().putExtra(
                EXTRA_ADDED_WIDGET,
                data,
            ),
        )
    }

    companion object {
        const val EXTRA_ADDED_WIDGET = "added_widget"

        fun start(context: Context, widgetId: Int) {
            val intent = Intent(context, AddWidgetStackWidgetActivity::class.java)
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)
            context.startActivity(intent)
        }
    }
}
