package xn.xxp.widget

import android.content.Context
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.drawable.AnimationDrawable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.RelativeSizeSpan
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import coil.decode.SvgDecoder
import xn.xxp.R
import xn.xxp.databinding.WidgetItemBoardBinding

import android.graphics.*
import android.graphics.drawable.VectorDrawable
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.applyCanvas
import coil.ImageLoader
import coil.load
import coil.request.ImageRequest
import coil.size.Size
import coil.transform.Transformation

/**
 * 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 = if (TextUtils.isEmpty(sensorName)) "" else (sensorName)
        viewBinding.sensorIcon.setImageResource(drawableResId)
    }

    fun setSensorInfo(sensorName: String?, url: String) {
        viewBinding.sensorName.text = if (TextUtils.isEmpty(sensorName)) "" else (sensorName)

//        val tintPaint = Paint().apply {
//            colorFilter = PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN)
//        }
        viewBinding.sensorIcon.load(url) {
            decoderFactory { result, options, _ -> SvgDecoder(result.source, options) }
            transformations(WhiteTintTransformation())
        }
//        Glide.with(this)
//            .`as`(PictureDrawable::class.java)
//            .transition(DrawableTransitionOptions.withCrossFade())
//            .listener(SvgSoftwareLayerSetter(tintPaint))
//            .load(url)
//            .into(viewBinding.sensorIcon)
    }

    class WhiteTintTransformation : Transformation {
        override val cacheKey: String = "white_tint"

        override suspend fun transform(input: Bitmap, size: Size): Bitmap {
            return input.apply {
                Canvas(this).drawColor(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
            }
        }
    }


    fun setSensorValue(value: String?, unit: String?, warning: Boolean, online: 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 (value == "异常") {
                viewBinding.sensorValue.setTextColor(Color.RED)
            }
            if (viewBinding.root.background != mAnimDrawable) {
                viewBinding.root.background = mAnimDrawable
            }
            if (!mAnimDrawable.isRunning) mAnimDrawable.start()
        } else {
            viewBinding.sensorValue.setTextColor(Color.WHITE)
            if (mAnimDrawable.isRunning) mAnimDrawable.stop()
            viewBinding.root.setBackgroundResource(R.mipmap.icon_sensor_none)
        }
        if (online) {
            viewBinding.layer.setBackgroundColor(Color.TRANSPARENT)
        } else {
            viewBinding.layer.setBackgroundColor(Color.GRAY)
        }
    }

    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_none)!!, 120)
            isOneShot = false
        }
    }

}