package club.clubk.ktag.apps.sharedservices

import android.content.Context
import android.util.AttributeSet
import androidx.preference.EditTextPreference

/**
 * An EditTextPreference that displays its current value as the summary,
 * with optional custom hint text when value is empty.
 */
class SummarizedEditTextPreference @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = androidx.preference.R.attr.editTextPreferenceStyle,
    defStyleRes: Int = 0
) : EditTextPreference(context, attrs, defStyleAttr, defStyleRes) {

    private val customHint: CharSequence?

    init {
        val typedArray = context.obtainStyledAttributes(
            attrs,
            R.styleable.SummarizedEditTextPreference,
            defStyleAttr,
            defStyleRes
        )
        try {
            customHint = typedArray.getString(R.styleable.SummarizedEditTextPreference_customHint)
        } finally {
            typedArray.recycle()
        }
    }

    override fun getSummary(): CharSequence? {
        val text = text
        return if (text.isNullOrEmpty()) {
            customHint ?: "Not set"
        } else {
            val summaryPattern = super.getSummary()
            if (summaryPattern != null) {
                String.format(summaryPattern.toString(), text)
            } else {
                text
            }
        }
    }
}
