package com.recordatorios.app

import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.recordatorios.app.databinding.ActivityWidgetConfigBinding

class WidgetConfigActivity : AppCompatActivity() {

    private lateinit var binding: ActivityWidgetConfigBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityWidgetConfigBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val appWidgetId = intent?.getIntExtra(
            AppWidgetManager.EXTRA_APPWIDGET_ID,
            AppWidgetManager.INVALID_APPWIDGET_ID
        ) ?: AppWidgetManager.INVALID_APPWIDGET_ID

        if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish()
            return
        }

        binding.btnConfigSave.setOnClickListener {
            val prefs = getSharedPreferences(TodayWidgetProvider.PREFS_WIDGET, Context.MODE_PRIVATE)
            prefs.edit()
                .putBoolean("widget_${appWidgetId}_show_time", binding.configShowTime.isChecked)
                .putBoolean("widget_${appWidgetId}_show_category", binding.configShowCategory.isChecked)
                .putInt(
                    "widget_${appWidgetId}_max_items",
                    when (binding.configChipGroupMax.checkedChipId) {
                        R.id.configMax5 -> 5
                        R.id.configMax15 -> 15
                        R.id.configMaxAll -> 0
                        else -> 10
                    }
                )
                .apply()

            val result = Intent().apply {
                putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
            }
            setResult(RESULT_OK, result)

            TodayWidgetProvider.updateAllWidgets(this)
            finish()
        }
    }
}
