package party.bami.eqfix.analysis;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.SystemClock;

import java.util.Arrays;

import party.bami.eqfix.channels.ChanMode;

public class PCMPlayer {
    private AudioTrack at;

    /**
     * Plays a given PCM.
     * @param pcm The PCM.
     * @param sampR The sample rate in Hz.
     * @param m The channel mode, STEREO or MONO.
     */
    public void play(float[] pcm, int sampR, ChanMode m) {
        int atMode = AudioFormat.CHANNEL_OUT_STEREO;
        switch (m) {
            case STEREO: atMode = AudioFormat.CHANNEL_OUT_STEREO;
                break;
            case MONO: atMode = AudioFormat.CHANNEL_OUT_MONO;
                break;
        }

        at = new AudioTrack(AudioManager.STREAM_MUSIC,
                sampR, atMode,
                AudioFormat.ENCODING_PCM_FLOAT,
                2 * pcm.length,
                AudioTrack.MODE_STREAM);
        at.write(pcm, 0, pcm.length, AudioTrack.WRITE_NON_BLOCKING);
        at.play();
    }

    /**
     * Plays a given PCM.
     * @param pcm The PCM.
     * @param sampR The sample rate in Hz.
     * @param m The channel mode, STEREO or MONO.
     */
    public void play(float[] pcm, int sampR, ChanMode m, int blocking) {
        if (blocking == AudioTrack.WRITE_NON_BLOCKING) {
            play(pcm, sampR, m);
            return;
        }

        int atMode = AudioFormat.CHANNEL_OUT_STEREO;
        switch (m) {
            case STEREO: atMode = AudioFormat.CHANNEL_OUT_STEREO;
                break;
            case MONO: atMode = AudioFormat.CHANNEL_OUT_MONO;
                break;
        }
        int bufferSize = sampR / 2 - 2;

        at = new AudioTrack(AudioManager.STREAM_MUSIC,
                sampR, atMode,
                AudioFormat.ENCODING_PCM_FLOAT,
                bufferSize * 2,
                AudioTrack.MODE_STREAM);

        for (int i = 0; i < pcm.length / bufferSize; i++) {
            float[] buffer = new float[bufferSize];
            System.arraycopy(pcm, i * bufferSize, buffer, 0, bufferSize);
            at.write(buffer, 0, bufferSize, AudioTrack.WRITE_BLOCKING);
            at.play();
        }
        at.release();
    }

    public void release() {
        at.release();
    }
}
