package com.dlc.eboard.ui.widget

import android.content.Context
import android.graphics.drawable.AnimationDrawable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.RelativeSizeSpan
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.dlc.eboard.R
import com.dlc.eboard.databinding.WidgetItemBoardBinding

/**
 * info
 *
 * @author ReiChin_
 */
class ItemBoardView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    ConstraintLayout(context, attrs, defStyleAttr) {

    private val viewBinding =
        WidgetItemBoardBinding.inflate(LayoutInflater.from(context), this, true)

    init {
        val typeArray = context.obtainStyledAttributes(attrs, R.styleable.HomeSensorView)
        val iconDrawable = typeArray.getDrawable(R.styleable.HomeSensorView_sensorIcon)
        if (null != iconDrawable) viewBinding.sensorIcon.setImageDrawable(iconDrawable)
        viewBinding.sensorName.text = typeArray.getString(R.styleable.HomeSensorView_sensorName)
        typeArray.recycle()
    }

    fun setSensorInfo(sensorName: String?, drawableResId: Int) {
        viewBinding.sensorName.text = sensorName
        viewBinding.sensorIcon.setImageResource(drawableResId)
    }

    fun setSensorInfo(sensorName: String?, url: String) {
        viewBinding.sensorName.text = sensorName
        Glide.with(this)
            .load(url)
            .into(viewBinding.sensorIcon)
    }

    fun setSensorValue(value: String?, unit: String?, warning: Boolean) {
        val formatVal = SpannableString("${value ?: ""}${unit ?: ""}")
        if (null != unit) {
            formatVal.setSpan(
                RelativeSizeSpan(0.8f),
                value?.length ?: 0,
                formatVal.length,
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            )
        }
        viewBinding.sensorValue.text = formatVal
//        if (warning) {
//            if (viewBinding.root.background != mAnimDrawable) {
//                viewBinding.root.background = mAnimDrawable
//            }
//            if (!mAnimDrawable.isRunning) mAnimDrawable.start()
//        } else {
//            if (mAnimDrawable.isRunning) mAnimDrawable.stop()
//            viewBinding.root.setBackgroundResource(R.mipmap.icon_sensor_normal)
//        }
    }

//    private val mAnimDrawable by lazy {
//        AnimationDrawable().apply {
//            addFrame(ContextCompat.getDrawable(context, R.mipmap.icon_sensor_waring)!!, 120)
//            addFrame(ContextCompat.getDrawable(context, R.mipmap.icon_sensor_normal)!!, 120)
//            isOneShot = false
//        }
//    }

}