package tk.zwander.widgetdrawer.activities.add

import android.appwidget.AppWidgetProviderInfo
import android.content.Context
import android.content.Intent
import tk.zwander.common.activities.add.IDrawerConfigureActivity
import tk.zwander.common.activities.add.ReconfigureWidgetActivity
import tk.zwander.common.data.WidgetData
import tk.zwander.common.data.WidgetSizeData
import tk.zwander.common.util.Event
import tk.zwander.common.util.createPersistablePreviewBitmap
import tk.zwander.common.util.eventManager
import tk.zwander.common.util.getCellHeightCompat
import tk.zwander.common.util.getCellWidthCompat
import tk.zwander.lockscreenwidgets.R

class ReconfigureDrawerWidgetActivity : ReconfigureWidgetActivity(), IDrawerConfigureActivity {
    companion object {
        fun launch(context: Context, id: Int, providerInfo: AppWidgetProviderInfo) {
            val intent = Intent(context, ReconfigureDrawerWidgetActivity::class.java)

            intent.putExtra(EXTRA_PREVIOUS_ID, id)
            intent.putExtra(EXTRA_PROVIDER_INFO, providerInfo)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

            context.startActivity(intent)
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        eventManager.sendEvent(Event.ShowDrawer)
    }

    override fun createWidgetData(id: Int, provider: AppWidgetProviderInfo, overrideSize: WidgetSizeData?): WidgetData {
        return WidgetData.widget(
            context = this,
            id = id,
            widgetProvider = provider.provider,
            label = provider.loadLabel(packageManager),
            icon = provider.createPersistablePreviewBitmap(this),
            size = overrideSize ?: run {
                val defaultColSpan = provider.getCellWidthCompat(display.dpToPx(width), colCount)
                    .coerceAtMost(colCount)

                val rowHeight = resources.getDimensionPixelSize(R.dimen.drawer_row_height)

                val defaultRowSpan = provider.getCellHeightCompat(rowHeight, rowCount)
                    .coerceAtLeast(10)
                    .coerceAtMost(rowCount)

                WidgetSizeData(defaultColSpan, defaultRowSpan)
            },
            profile = provider.profile,
        )
    }
}