package com.efounder.chat.view;

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


import com.efounder.chat.R;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ThreadManager;

import java.util.LinkedList;
import java.util.List;

/**
 * 语音录制的动画效果
 *
 */
public class LineWaveVoiceView extends View {
    private static final String TAG = LineWaveVoiceView.class.getSimpleName();

    private Paint paint;
    //矩形波纹颜色
    private int lineColor;
    //矩形波纹宽度
    private float lineWidth;
    private float textSize;
    private static final String DEFAULT_TEXT = " 00:00 ";
    private String text = DEFAULT_TEXT;
    private int textColor;
    private boolean isStart = false;
    private Runnable mRunable;

    private int LINE_W = 9;//默认矩形波纹的宽度，9像素, 原则上从layout的attr获得
    private int MIN_WAVE_H = 2;//最小的矩形线高，是线宽的2倍，线宽从lineWidth获得
    private int MAX_WAVE_H = 7;//最高波峰，是线宽的4倍

    //默认矩形波纹的高度，总共10个矩形，左右各有10个
    private int[] DEFAULT_WAVE_HEIGHT = {2, 3, 4, 3, 2, 2, 2, 2, 2, 2};
    private LinkedList<Integer> mWaveList = new LinkedList<>();

    private RectF rectRight = new RectF();//右边波纹矩形的数据，10个矩形复用一个rectF
    private RectF rectLeft = new RectF();//左边波纹矩形的数据

    LinkedList<Integer> list = new LinkedList<>();
    //振幅
    private float maxAmp = 0;
    private static final int UPDATE_INTERVAL_TIME = 110;//100ms更新一次

    public LineWaveVoiceView(Context context) {
        super(context);
    }

    public LineWaveVoiceView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LineWaveVoiceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paint = new Paint();
        //初始矩形大小集合
        resetList(list, DEFAULT_WAVE_HEIGHT);
        //开启接收绘制
        receiveDraw();
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.LineWaveVoiceView);
        lineColor = mTypedArray.getColor(R.styleable.LineWaveVoiceView_voiceLineColor, Color.parseColor("#ff9c00"));
        lineWidth = mTypedArray.getDimension(R.styleable.LineWaveVoiceView_voiceLineWidth, LINE_W);
        textSize = mTypedArray.getDimension(R.styleable.LineWaveVoiceView_voiceTextSize, 42);
        textColor = mTypedArray.getColor(R.styleable.LineWaveVoiceView_voiceTextColor, Color.parseColor("#666666"));
        mTypedArray.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int widthcentre = getWidth() / 2;
        int heightcentre = getHeight() / 2;
        //更新时间
        paint.setStrokeWidth(0);
        paint.setColor(textColor);
        paint.setTextSize(textSize);
        float textWidth = paint.measureText(text)+50;
        canvas.drawText(text, widthcentre - textWidth/3, heightcentre - (paint.ascent() + paint.descent())/2, paint);

        //更新左右两边的波纹矩形
        paint.setColor(lineColor);
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(lineWidth);
        paint.setAntiAlias(true);
        //矩形间的间隔
        int space = 0;
        for(int i = 0 ; i < 10 ; i++) {
            space = (int) (i*2);
                   //右边矩形
                   rectRight.left = widthcentre + 2 * space * lineWidth + textWidth / 2 + lineWidth;
                   rectRight.top = heightcentre - list.get(i) * lineWidth / 2;
                   rectRight.right = widthcentre  + 2 * space * lineWidth +2 * lineWidth + textWidth / 2+2;
                   rectRight.bottom = heightcentre + list.get(i) * lineWidth /2;

                   //左边矩形
                   rectLeft.left = widthcentre - (2 * space * lineWidth +  textWidth / 2 + 2 * lineWidth );
                   rectLeft.top = heightcentre - list.get(i) * lineWidth / 2;
                   rectLeft.right = widthcentre  -( 2 * space * lineWidth + textWidth / 2 + lineWidth)+3;
                   rectLeft.bottom = heightcentre + list.get(i) * lineWidth / 2;
                   //绘制两边的矩形
                   canvas.drawRect(rectRight,  paint);
                   canvas.drawRect(rectLeft,  paint);
               }

    }

    /**
     * 设置声线矩形的
     * @param maxAmp
     */
    public void setMaxAmp(float maxAmp) {
        this.maxAmp = maxAmp;
    }

    public synchronized void refreshElement() {
//        LogUtils.i(TAG, "refreshElement, maxAmp " + maxAmp);
        int waveH = MIN_WAVE_H + Math.round(maxAmp * (MAX_WAVE_H -2));//wave 在 2 ~ 7 之间
//        LogUtils.i(TAG,"waveH------->"+waveH);
        list.add(0, waveH);
        maxAmp = 0;
        list.removeLast();
    }

    /**
     * 开始状态下不断绘制矩形
     */
    private void receiveDraw(){
        mRunable = new Runnable() {
            @Override
            public void run() {
                while (isStart){
                    try {
                        Thread.sleep(UPDATE_INTERVAL_TIME);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //添加绘制集合
                    refreshElement();
                    //更新view状态
                    postInvalidate();
                }
            }
        };
    }

    /**
     * 设置 text
     * @param text
     */
    public synchronized void setText(String text) {
        this.text = text;
        postInvalidate();
    }

    /**
     * 开始录音状态  开启绘制线程
     */
    public synchronized void startRecord(){
        isStart = true;
        ThreadManager.getThreadPool().execute(mRunable);
    }

    /**
     * 停止录音
     */
    public synchronized void stopRecord(){
        isStart = false;
        mWaveList.clear();
        resetList(list, DEFAULT_WAVE_HEIGHT);
        text = DEFAULT_TEXT;
        ThreadManager.getThreadPool().cancel(mRunable);
        postInvalidate();
    }

    /**
     * 设置默认绘制集和
     * @param list 默认绘制集合
     * @param array 默认数据数组
     */
    private void resetList(List list, int[] array) {
        list.clear();
        for(int i = 0 ; i < array.length; i++ ){
            list.add(array[i]);
        }
    }
}