package com.abbidot.tracker.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatSeekBar
import com.abbidot.baselibrary.util.LogUtil

/**
 * Created  by .yzq on 2022/1/6/006.
 *
 * @link
 * @description: 垂直滑动滚动条,从上往下滑动
 */
class VerticalTopToBottomSeekBar : AppCompatSeekBar {

    private var mOnSeekBarChangeListener: OnSeekBarChangeListener? = null

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

    /**
     *onDraw事件中旋转画布，由水平变垂直
     */
    @Synchronized
    override fun onDraw(canvas: Canvas) {
        canvas.rotate(90f)
        canvas.translate(0f, -width.toFloat())
        super.onDraw(canvas)
    }

    /**
     * measure事件中重新计算控件尺寸，对换宽高值
     */
    @Synchronized
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = measuredWidth
        val height = measuredHeight
        setMeasuredDimension(width, height)
    }

    /**
     * 切记加上尺寸变更时的事件，变更对换宽高值
     */
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(h, w, oldh, oldw)
    }

    /**
     * 最后重载—下滑动事件，重新计算progress值
     */
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (!isEnabled) return false
        when (event.action) {
            MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP -> {
                if (max <= 0) return true
                //因为我这是向下滑动的，所以最大值乘Y轴的滑动比例得到上面值即可
                progress = (max * event.y / height).toInt()
                LogUtil.d("$progress")
                onSizeChanged(width, height, 0, 0)
                if (null != mOnSeekBarChangeListener) {
                    mOnSeekBarChangeListener!!.onProgressChanged(progress)
                    //手指停止按屏幕，离开屏幕
                    if (event.action == MotionEvent.ACTION_UP) {
                        mOnSeekBarChangeListener!!.onStopChanged(progress)
                    }
                }
            }
        }
        return true
    }

    /**
     * 调用setProgress(int progress)失效，滚动条没有变化
     */
    @Synchronized
    override fun setProgress(progress: Int) {
        super.setProgress(progress)
        onSizeChanged(width, height, 0, 0)
    }

    fun setOnSeekBarChangeProgressListener(l: OnSeekBarChangeListener) {
        mOnSeekBarChangeListener = l
    }


    interface OnSeekBarChangeListener {
        fun onProgressChanged(progress: Int)
        fun onStopChanged(progress: Int)
    }
}