package com.yzx.ebrand.widget

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.widget.LinearLayoutCompat
import com.yzx.ebrand.R
import kotlinx.android.synthetic.main.view_time.view.*
import org.jetbrains.anko.dip

class ClassStar(context: Context, attrs: AttributeSet) :
    FrameLayout(context, attrs) {

    lateinit var p: LinearLayoutCompat

    init {
        p = LayoutInflater.from(context).inflate(R.layout.class_star, null) as LinearLayoutCompat
        addView(p)

//        setStar()
    }

    @SuppressLint("SetTextI18n")
    fun setStar(num: Int = 1) {
        for (i in 0 until p.childCount) {
            val child = p.getChildAt(i)
            child.clearAnimation()
        }
        p.removeAllViews()
        p.clearAnimation()
        if (num <= 0) {
            return
        }


        val resId = when {
            num >= 6 -> R.mipmap.icon_gold
            num == 5 -> R.mipmap.icon_silvery
            else -> R.mipmap.icon_coppery
        }
        for (i in 1..num) {
            val startView = ImageView(context)
            val lp = LinearLayoutCompat.LayoutParams(dip(35), dip(32))
            lp.leftMargin = dip(15)
            lp.setMargins(dip(15), 0, 0, 0)
            startView.setImageResource(resId)
            startView.clearAnimation()
//            startView.setBackgroundResource(R.drawable.gold_shadow)
//            (startView.background as AnimationDrawable).start()
            if (num >= 6) {
                flicker(startView, i, num)
            }
            p.addView(startView, lp)
        }
        p.requestLayout()

    }

    private fun flicker(startView: ImageView, index: Int, total: Int) {
        val anim = AlphaAnimation(0.3f, 1f)
        anim.duration = 200L
        anim.interpolator = LinearInterpolator()
        anim.repeatCount = Animation.INFINITE
        anim.repeatMode = Animation.REVERSE
        anim.startOffset = (index - 1) * (200L/total)
        startView.animation = anim
    }
}