package net.heartshield.sensors;

import android.support.test.runner.AndroidJUnit4;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

/**
 * AudioSensor tests which will execute on an Android device.
 */
@RunWith(AndroidJUnit4.class)
public class AudioSensorTest {

    class AudioLagTester {
        boolean gotFailedState = false;
        Exception exception = null;
    }

    /**
     * provoke audio lag, to test audio lag detection
     */
    //@Test(expected=IndexOutOfBoundsException.class)
    @Test
    public void testAudioLag() throws Exception {
        final AudioSensor sensor = new AudioSensor(10.0);
        final AudioLagTester tester = new AudioLagTester();

        sensor.setListener(new ISensor.Listener() {
            @Override
            public void onData(int offset, int length) {

            }

            @Override
            public void onState(ISensor.State newState) {
                if(newState == ISensor.State.FAILED) {
                    tester.gotFailedState = true;
                    tester.exception = sensor.getError();
                }
            }
        });

        /*
         * Test the "audio lag" detection by read()ing full buffer sizes.
         * Due to scheduling jitter, doing so will quickly result in two read()s spaced too far away in time.
         */
        sensor.setReadToBufSizeRatio(1);

        sensor.start();
        Thread.sleep(AudioSensor.START_TIME_MS); // wait for audio lag to occur
        sensor.stop();

        assertTrue("should emit FAILED state", tester.gotFailedState);
        assertTrue("should return AudioLagException error", tester.exception != null && tester.exception.getCause() instanceof AudioSensor.AudioLagException);
    }
}
