package com.centralcloud.oncall.sms

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.centralcloud.oncall.R
import java.text.DateFormat
import java.util.Date

/**
 * Standalone settings screen for the SMS-relay feature.
 *
 * Lives outside the main `SettingsActivity` (which is a large monolith with
 * its own pattern of inner-fragment classes) to keep this PR self-contained.
 * Launch it via adb during bring-up:
 *
 *     adb shell am start -n com.centralcloud.oncall/.sms.SmsRelaySettingsActivity
 *
 * Once the broader settings nav is ready, a Preference entry in
 * main_preferences.xml can deep-link here with:
 *
 *     <Preference
 *         app:title="SMS Relay"
 *         app:fragment="com.centralcloud.oncall.sms.SmsRelaySettingsActivity$Fragment"/>
 *
 * Requires a `<activity>` entry in AndroidManifest.xml — added together with
 * the SmsRelayReceiver registration in the pending manifest commit.
 */
class SmsRelaySettingsActivity : AppCompatActivity() {

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

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        title = "SMS Relay"

        if (savedInstanceState == null) {
            supportFragmentManager
                .beginTransaction()
                .replace(android.R.id.content, Fragment())
                .commit()
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        finish()
        return true
    }

    class Fragment : PreferenceFragmentCompat() {

        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            // Point at the same SharedPreferences file that SmsRelayPreferences
            // reads/writes so this fragment edits the live config directly.
            preferenceManager.sharedPreferencesName = "sms_relay_prefs"
            setPreferencesFromResource(R.xml.sms_relay_preferences, rootKey)
        }

        override fun onResume() {
            super.onResume()
            refreshStatus()
        }

        private fun refreshStatus() {
            val prefs = SmsRelayPreferences(requireContext())

            findPreference<Preference>("status_summary")?.summary =
                when (val ms = prefs.lastForwardAtMs) {
                    0L -> "Never"
                    else -> DateFormat
                        .getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM)
                        .format(Date(ms))
                }

            findPreference<Preference>("failure_summary")?.summary =
                prefs.failureCount24h.let { n ->
                    if (n == 0) "None in the last 24h"
                    else "$n in the last 24h"
                }
        }
    }
}
