package tk.zwander.common.activities.add

import android.appwidget.AppWidgetProviderInfo
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.compose.ui.unit.IntSize
import tk.zwander.common.data.WidgetData
import tk.zwander.common.data.WidgetTileInfo
import tk.zwander.common.util.prefManager

/**
 * Manage selecting the widget for a given tile.
 */
class AddTileWidgetActivity : AddWidgetActivity() {
    companion object {
        const val EXTRA_TILE_ID = "tile_id"

        const val NO_ID = -1

        fun createIntent(context: Context, tileId: Int): Intent {
            return Intent(context, AddTileWidgetActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                putExtra(EXTRA_TILE_ID, tileId)
            }
        }
    }

    override val fullSize: IntSize = IntSize(width.toInt(), height.toInt())

    override val colCount: Int
        get() = 1
    override val rowCount: Int
        get() = 1
    override val width: Float
        get() = 300f
    override val height: Float
        get() = 300f

    override val showShortcuts: Boolean
        get() = false

    override var currentWidgets: Set<WidgetData>
        get() = []
        set(_) {}

    override val currentIds: Collection<Int>
        get() = prefManager.customTiles.values.map { it.widgetId }

    private val tileId by lazy { intent.getIntExtra(EXTRA_TILE_ID, NO_ID) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (tileId == NO_ID) {
            finish()
            return
        }
    }

    /**
     * Add the specified widget to the frame and save it to SharedPreferences.
     *
     * @param id the ID of the widget to be added
     */
    override fun addNewWidget(id: Int, provider: AppWidgetProviderInfo) {
        prefManager.customTiles = prefManager.customTiles.apply {
            this[tileId] = WidgetTileInfo(id)
        }
        finish()
    }
}
