package party.bami.eqfix;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Toast;

import java.util.Arrays;
import java.util.Vector;

public class VisualizerView extends View {

    private float[] mBytes;

    private float[] mPoints;

    private Rect mRect = new Rect();
    private Paint mForePaint = new Paint();

    public VisualizerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mBytes = null;
        mForePaint.setStrokeWidth(1);
        mForePaint.setColor(Color.BLACK);

    }

    public void updateVisualizer(byte[] bytes) {
        float[] tmp = new float[bytes.length];
        for (int i = 0; i < bytes.length; i++)
            tmp[i] = (float)bytes[i];
        mBytes = tmp;
        invalidate();
    }

    public void updateVisualizer(short[] bytes) {
        float[] tmp = new float[bytes.length];
        for (int i = 0; i < bytes.length; i++)
            tmp[i] = (float)bytes[i];
        mBytes = tmp;
        invalidate();
    }

    public void updateVisualizer(int[] bytes) {
        float[] tmp = new float[bytes.length];
        for (int i = 0; i < bytes.length; i++)
            tmp[i] = (float)bytes[i];
        mBytes = tmp;
        invalidate();
    }

    public void updateVisualizer(float[] bytes) {
        mBytes = bytes;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2, mForePaint);

        mForePaint.setARGB(255, 40, 40, 255);

        if (mBytes == null)
            return;

        if (mPoints == null || mPoints.length < mBytes.length * 4) {
            mPoints = new float[mBytes.length * 4];
        }

        for (int i = 0; i < mBytes.length; i++)
            mBytes[i] *= 10f;

        mRect.set(0, 0, getWidth(), getHeight());
        for (int i = 0; i < mBytes.length - 1; i++) {
            mPoints[i * 4] = mRect.width() * i / (mBytes.length - 1);
            mPoints[i * 4 + 1] = mRect.height() / 3 + (mBytes[i] + 128);
            mPoints[i * 4 + 2] = mRect.width() * (i + 1) / (mBytes.length - 1);
            mPoints[i * 4 + 3] = mRect.height() / 3 + (mBytes[i + 1] + 128);
        }

        canvas.drawLines(mPoints, mForePaint);
    }
}