package com.zxhyis.toolss.widget

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import com.zxhyis.toolss.ui.home.MainActivity


object WidgetHelper {

    fun Context.requestToPinWidget() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val appWidgetManager: AppWidgetManager? = getSystemService(AppWidgetManager::class.java) as AppWidgetManager?
            val myProvider = ComponentName(this, NewAppWidget::class.java)
            if (appWidgetManager != null) {
                if (appWidgetManager.isRequestPinAppWidgetSupported) {
                    val pinnedWidgetCallbackIntent = Intent(this, MainActivity::class.java)
                    val successCallback = PendingIntent.getBroadcast(
                        this, 0, pinnedWidgetCallbackIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
                    )
                    appWidgetManager.requestPinAppWidget(myProvider, null, successCallback)
                }
            }
        }
    }
}