package fortuna.entropySources.microphone;

/**
 *
 * @author Viliam Krizan
 */

import fortuna.entropySources.EntropySource;
import javax.sound.sampled.*;


public class CaptureMicrophoneData extends EntropySource{

    
    
    AudioFormat audioFormat;
    TargetDataLine targetDataLine;
    
    public CaptureMicrophoneData(){
        try {
            audioFormat = getAudioFormat();
            DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
            targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
            targetDataLine.open(audioFormat);
            targetDataLine.start();
        } catch (Exception e) {
            System.out.println(e);
            System.exit(0);
        }
    }
    
    private AudioFormat getAudioFormat() {
        float sampleRate = 192000.0F;
        //8000,11025,16000,22050,44100...
        int sampleSizeInBits = 16;
        //8,16
        int channels = 1;
        //1,2
        boolean signed = true;
        //bits are signed for true(znamena ze su znamienkove)
        //true,false
        boolean bigEndian = true;
        //urcuje kde sa nachadya LSB
        //true,false
        return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
    }

    @Override
    public void run() {
        super.run();
        
        byte tempBuffer[] = new byte[1000];
            
        try {
            while (running) {
                //reading data from targetDataLine and saving into tempBuffer array
                //This method blocks until the requested amount of data has been read
                int cnt = targetDataLine.read(tempBuffer,0,tempBuffer.length);
                if (cnt > 0) {
                    //if the tempBuffer has been override with fresh data
                    //save these data into correct pool
                    acumulator.saveToPool(tempBuffer, actualPool);
                    poolCounterIncrement();
                }
                    
            } 
        } catch (Exception e) {
            //System.out.println(e);
            //System.exit(0);
        }
            
    }
    
}
