package club.clubk.ktag.apps.sharedservices

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.annotation.XmlRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NavUtils

/**
 * Base activity for displaying preference screens.
 * Subapps can use this directly via [createIntent] or subclass for custom behavior.
 */
open class BaseSettingsActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)

        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        if (savedInstanceState == null) {
            val preferencesResId = intent.getIntExtra(EXTRA_PREFERENCES_RES_ID, 0)
            if (preferencesResId != 0) {
                supportFragmentManager.beginTransaction()
                    .replace(R.id.settings_container, BaseSettingsFragment.newInstance(preferencesResId))
                    .commit()
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            NavUtils.navigateUpFromSameTask(this)
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    companion object {
        internal const val EXTRA_PREFERENCES_RES_ID = "preferences_res_id"

        /**
         * Create an Intent to launch the settings activity with the given preferences XML.
         */
        @JvmStatic
        fun createIntent(context: Context, @XmlRes preferencesResId: Int): Intent {
            return createIntent(context, preferencesResId, BaseSettingsActivity::class.java)
        }

        /**
         * Create an Intent to launch a settings activity subclass with the given preferences XML.
         */
        @JvmStatic
        fun <T : BaseSettingsActivity> createIntent(
            context: Context,
            @XmlRes preferencesResId: Int,
            activityClass: Class<T>
        ): Intent {
            return Intent(context, activityClass).apply {
                putExtra(EXTRA_PREFERENCES_RES_ID, preferencesResId)
            }
        }
    }
}
