package com.sd.cavphmi.ui.view

import android.animation.Animator
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView

/**
 * 航向角
 * */
class HeadAngelView : AppCompatImageView {

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init()
    }

    private lateinit var rotationAnimator: ObjectAnimator
    var start = 0f
    var end = 0f
    var cur = 0f

    //    private var emitter: ObservableEmitter<Float>? = null
    fun init() {
        rotationAnimator = ObjectAnimator.ofFloat(this, "rotation", start)
        rotationAnimator.setDuration(300) // 设置动画持续时间，单位为毫秒
        rotationAnimator.addUpdateListener(animatorUpdateListener)
//        Observable.create<Float> { emitter ->
//            this.emitter = emitter
//        }.throttleLast(1, TimeUnit.SECONDS)
//            .subscribeOn(AndroidSchedulers.mainThread())
//            .subscribe({ next ->
//                println("----------next = ${next}")
//                rotationAnimator.cancel()
//                rotationAnimator.setFloatValues(cur, end)
//                rotationAnimator.start()
//            }, {}, {})
    }


    fun setFirst() {
        rotationAnimator.cancel()
        rotationAnimator.setFloatValues(cur, start)
        rotationAnimator.start()
    }

    fun setHeadAngel(newHead: Float) {
        if (newHead < 0f)
            return
        end = newHead
//        emitter?.onNext(end)
        rotationAnimator.cancel()
        rotationAnimator.setFloatValues(cur, end)
        rotationAnimator.start()
    }


    private var animatorListener = object : Animator.AnimatorListener {
        override fun onAnimationStart(animation: Animator) {
        }

        override fun onAnimationEnd(animation: Animator) {
        }

        override fun onAnimationCancel(animation: Animator) {
        }

        override fun onAnimationRepeat(animation: Animator) {
        }

    }


    private var animatorUpdateListener = object : ValueAnimator.AnimatorUpdateListener {
        override fun onAnimationUpdate(animation: ValueAnimator) {
//            println("------------animation = ${animation.animatedValue}")
            cur = animation.animatedValue as Float
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
//        rotationAnimator.removeAllListeners()
        rotationAnimator.removeUpdateListener(animatorUpdateListener)
    }

}