package com.casic.dcms.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.casic.dcms.R;
import com.casic.dcms.base.BaseApplication;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class VoicePlayView extends View {

    private static final String TAG = "VoicePlayView";
    private Paint paint;
    //跳动指针的集合
    private List<Pointer> pointers = new ArrayList<>();
    private boolean isPlaying = false;
    private Thread playThread;
    private float basePointY;
    //指针间的间隙  默认5dp
    private float pointerPadding = QMUIDisplayHelper.dp2px(BaseApplication.getInstance(), 3);
    //每个指针的宽度 默认3dp
    private float pointerWidth = QMUIDisplayHelper.dp2px(BaseApplication.getInstance(), 5);

    public VoicePlayView(Context context) {
        this(context, null);
    }

    public VoicePlayView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VoicePlayView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initConfig(context, attrs);
    }

    private void initConfig(Context context, AttributeSet attrs) {
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.VoicePlayView);
        int color = typedArray.getColor(R.styleable.VoicePlayView_indicatorColor, Color.RED);
        int indicatorNumber = typedArray.getInt(R.styleable.VoicePlayView_indicatorNumber, 10);

        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(color);

        typedArray.recycle();

        Random random = new Random();
        if (pointers != null) {
            pointers.clear();
        }
        for (int i = 0; i < indicatorNumber; i++) {
            //创建指针对象，利用0~1的随机数 乘以 可绘制区域的高度。作为每个指针的初始高度。
            pointers.add(new Pointer((float) (0.1 * (random.nextInt(10) + 1) * (getHeight() - getPaddingBottom() - getPaddingTop()))));
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        //获取逻辑原点的，也就是画布左下角的坐标。这里减去了paddingBottom的距离
        basePointY = getHeight() - getPaddingBottom();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //将x坐标移动到逻辑原点，也就是左下角
        float basePointX = 0f + getPaddingLeft();
        for (int i = 0; i < pointers.size(); i++) {
            //绘制指针，也就是绘制矩形
            canvas.drawRect(basePointX,
                    basePointY - pointers.get(i).getHeight(),
                    basePointX + pointerWidth,
                    basePointY,
                    paint);
            basePointX += (pointerPadding + pointerWidth);
        }
    }

    /**
     * 开始播放
     */
    public void start() {
        if (!isPlaying) {
            if (playThread == null) {//开启子线程
                playThread = new Thread(new PlayRunnable());
                playThread.start();
            }
            isPlaying = true;//控制子线程中的循环
        }
    }

    /**
     * 停止子线程，并刷新画布
     */
    public void stop() {
        isPlaying = false;
        invalidate();
    }

    /**
     * 处理子线程发出来的指令，然后刷新布局
     */
    private Handler invalidateHandler = new Handler(msg -> {
        invalidate();
        return false;
    });

    public class PlayRunnable implements Runnable {

        @Override
        public void run() {
            for (float i = 0; i < Integer.MAX_VALUE; ) {//创建一个死循环，每循环一次i+0.1
                try {
                    for (int j = 0; j < pointers.size(); j++) { //循环改变每个指针高度
                        float rate = (float) Math.abs(Math.sin(i + j));//利用正弦有规律的获取0~1的数。
                        pointers.get(j).setHeight((basePointY - getPaddingTop()) * rate); //rate 乘以 可绘制高度，来改变每个指针的高度
                    }
                    Thread.sleep(40);
                    if (isPlaying) { //控制开始/暂停
                        invalidateHandler.sendEmptyMessage(0);
                        i += 0.1;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private static class Pointer {
        private float height;

        Pointer(float height) {
            this.height = height;
        }

        public float getHeight() {
            return height;
        }

        public void setHeight(float height) {
            this.height = height;
        }
    }
}
