package tk.zwander.common.activities.add

import android.annotation.SuppressLint
import android.appwidget.AppWidgetProviderInfo
import android.os.Build
import android.os.Bundle
import com.android.internal.widget.RecyclerView
import tk.zwander.common.activities.DismissOrUnlockActivity
import tk.zwander.common.host.WidgetHostCompat
import tk.zwander.common.util.appWidgetManager
import tk.zwander.common.util.logUtils

abstract class ReconfigureWidgetActivity : BaseBindWidgetActivity() {
    companion object {
        const val EXTRA_PREVIOUS_ID = "previous_id"
        const val EXTRA_PROVIDER_INFO = "provider_info"
    }

    protected val prevId by lazy { intent.getIntExtra(EXTRA_PREVIOUS_ID, WidgetHostCompat.INVALID_WIDGET_ID) }
    private val providerInfo by lazy {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra(EXTRA_PROVIDER_INFO, AppWidgetProviderInfo::class.java)
        } else {
            @Suppress("DEPRECATION")
            intent.getParcelableExtra(EXTRA_PROVIDER_INFO) as? AppWidgetProviderInfo?
        }
    }
    override val deleteOnConfigureError: Boolean = false

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

        val providerInfo = providerInfo

        if (prevId == WidgetHostCompat.INVALID_WIDGET_ID || providerInfo == null) {
            finish()
            return
        }

        DismissOrUnlockActivity.launch(this)

        if (appWidgetManager.getAppWidgetInfo(prevId)?.provider == providerInfo.provider) {
            configureWidget(prevId, providerInfo)
        } else {
            tryBindWidget(providerInfo, widgetHost.allocateAppWidgetId())
        }
    }

    @SuppressLint("NewApi")
    override fun tryBindWidget(info: AppWidgetProviderInfo, id: Int) {
        val canBind = appWidgetManager.bindAppWidgetIdIfAllowed(id, info.provider)

        if (!canBind) getWidgetPermission(id, info.provider)
        else {
            if (info.configure != null) {
                configureWidget(id, info)
            } else {
                addNewWidget(id, info)
            }
        }
    }

    override fun configureWidget(id: Int, provider: AppWidgetProviderInfo) {
        DismissOrUnlockActivity.launch(this, false)
        super.configureWidget(id, provider)
    }

    override fun addNewWidget(id: Int, provider: AppWidgetProviderInfo) {
        val newSet = currentWidgets.toMutableList()

        val oldWidgetIndex = newSet.indexOfFirst { it.id == prevId }

        val oldWidget = if (oldWidgetIndex != RecyclerView.NO_POSITION) newSet.removeAt(oldWidgetIndex) else null

        val widget = createWidgetData(id, provider, oldWidget?.safeSize)

        val safeIndex =
            if (oldWidgetIndex != RecyclerView.NO_POSITION) oldWidgetIndex else newSet.lastIndex.run {
                if (this == RecyclerView.NO_POSITION) 0 else this
            }

        newSet.add(safeIndex, widget)

        logUtils.debugLog("Removed old widget from $oldWidgetIndex ($safeIndex) and added new one $widget")

        currentWidgets = LinkedHashSet(newSet)

        finish()
    }
}
