package com.dano.test1.util

import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.AbsListView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.TextView
import androidx.core.widget.TextViewCompat

fun TextView.setTextSizePercentOfScreenHeight(percentOfHeight: Float) {
    val dm = context.resources.displayMetrics
    val sp = (dm.heightPixels * percentOfHeight) / dm.scaledDensity
    TextViewCompat.setAutoSizeTextTypeWithDefaults(this, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE)
    setTextSize(TypedValue.COMPLEX_UNIT_SP, sp)
}

fun <T> Spinner.setupSpinner(items: List<T>, selectedItem: T?) {
    val dm = context.resources.displayMetrics

    fun spFromScreenHeight(percent: Float): Float = (dm.heightPixels * percent) / dm.scaledDensity
    fun pxFromSp(sp: Float): Int = (sp * dm.scaledDensity).toInt()

    val textSp = spFromScreenHeight(0.0275f)
    val textPx = pxFromSp(textSp)
    val vPadPx = (textPx * 0.50f).toInt()
    val rowHeight = (textPx * 2.20f + 2 * vPadPx).toInt()

    val adapter = object : ArrayAdapter<T>(context, android.R.layout.simple_spinner_item, items) {
        private fun styleRow(tv: TextView, forceHeight: Boolean) {
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSp)
            tv.includeFontPadding = true
            tv.setLineSpacing(0f, 1.2f)
            tv.gravity = (tv.gravity and Gravity.HORIZONTAL_GRAVITY_MASK) or Gravity.CENTER_VERTICAL
            tv.setPadding(tv.paddingLeft, vPadPx, tv.paddingRight, vPadPx)
            tv.minHeight = rowHeight
            tv.isSingleLine = true
            if (forceHeight) {
                val lp = tv.layoutParams
                if (lp == null || lp.height <= 0) {
                    tv.layoutParams = AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, rowHeight)
                } else {
                    lp.height = rowHeight
                }
            }
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            val v = super.getView(position, convertView, parent) as TextView
            styleRow(v, forceHeight = false)
            return v
        }

        override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
            val v = super.getDropDownView(position, convertView, parent) as TextView
            styleRow(v, forceHeight = true)
            return v
        }
    }

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    this.adapter = adapter
    setPadding(paddingLeft, vPadPx, paddingRight, vPadPx)
    minimumHeight = rowHeight
    requestLayout()

    selectedItem?.let {
        val index = items.indexOf(it)
        if (index >= 0) setSelection(index)
    }
}
