package net.heartshield.data;

import junit.framework.TestCase;

import java.io.IOException;

/**
 * @author David Madl (git@abanbytes.eu)
 * @date 2017-05-05
 */
public class SyncTaskQueueTest extends TestCase {
    private class TestResults {
        boolean finished = false;
        int synced;
        int candidates;
    }

    public void testSingleFullSync() {
        final Measurement mockMeasurement = new Measurement("01234567");
        mockMeasurement.series = new MeasurementSeries();

        MockMeasurementDataManager manager = new MockMeasurementDataManager() {
            @Override
            public Measurement retrieve(MeasurementId id) throws IOException {
                if(id.equals(mockMeasurement.getId()))
                    return mockMeasurement;
                return super.retrieve(id);
            }

            @Override
            public byte[] retrieveAudio(MeasurementId id) throws IOException {
                if(id.equals(mockMeasurement.getId()))
                    return new byte[0];
                return super.retrieveAudio(id);
            }

            @Override
            public MeasurementSummary[] list() {
                MeasurementSummary summary = mockMeasurement.getSummary();
                if(summary.status != MeasurementSummary.Status.OFFLINE)
                    throw new AssertionError("empty Measurement must have OFFLINE status summary");
                return new MeasurementSummary[] { summary };
            }
        };
        MeasurementDataManager.SyncTaskQueue queue = new MeasurementDataManager.SyncTaskQueue(manager);

        final TestResults results = new TestResults();

        queue.setListener(new MeasurementDataManager.SyncTaskQueue.SyncListener() {
            @Override
            public void onProgress(int synced, int candidates) {
                System.out.println("onProgress(). synced/candidates = " + synced + "/" + candidates);
            }

            @Override
            public void onFinished(int synced, int candidates) {
                System.out.println("onFinished(). synced/candidates = " + synced + "/" + candidates);
                results.finished = true;
                results.synced = synced;
                results.candidates = candidates;
            }
        });

        queue.start();

        if(!manager.created)
            throw new AssertionError("not created");
        if(!manager.putAudio)
            throw new AssertionError("not putAudio");

        assertTrue(results.finished);
        assertEquals(1, results.synced);
        assertEquals(1, results.candidates);
    }
}
