package net.heartshield.filter;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * Helper util to load audio on PC.
 *
 * @author David Madl (git@abanbytes.eu)
 * @date 2017-03-29
 */
public class AudioHelper {
    AudioInputStream ais;

    int frameRate;
    int frameSize;
    int channels;
    int bps;

    public AudioHelper(String fname) {
        try {
            ais = AudioSystem.getAudioInputStream(new File(fname));
            init(ais);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedAudioFileException e) {
            throw new RuntimeException(e);
        }
    }

    public AudioHelper(InputStream inputStream) {
        try {
            ais = AudioSystem.getAudioInputStream(inputStream);
            init(ais);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedAudioFileException e) {
            throw new RuntimeException(e);
        }
    }

    private void init(AudioInputStream ais) {
        AudioFormat af = ais.getFormat();
        frameRate = (int)af.getFrameRate();
        frameSize = af.getFrameSize();
        channels = af.getChannels();
        bps = af.getSampleSizeInBits();
    }

    public int getFps() { return frameRate; }

    public short[] readAudio() {
        try {
            return internalReadAudio();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedAudioFileException e) {
            throw new RuntimeException(e);
        }
    }

    private short[] internalReadAudio() throws IOException, UnsupportedAudioFileException {

        /*
        System.out.println("Frame Rate: " + frameRate);
        System.out.println("Frame Size: " + frameSize);
        //System.out.println("Buffer Size: " + bufSize);
        System.out.println("Channels: " + channels);
        System.out.println("Bits per sample: " + bps);
        */

        List<Short> buf = new ArrayList<>();

        byte[] data = new byte[2048];
        int bytesRead;

        while((bytesRead = ais.read(data, 0, data.length)) != -1) {
            for(int i = 0; i < bytesRead; i += 2)
                buf.add((short) (data[i] + 256 * data[i+1]));
        }

        short[] arr = new short[buf.size()];
        for(int i = 0; i < arr.length; i++)
            arr[i] = buf.get(i);
        return arr;
    }
}
