package org.multiverse.commitbarriers;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.multiverse.TestThread;

import static org.junit.Assert.*;
import static org.multiverse.TestUtils.*;
import static org.multiverse.api.TxnThreadLocal.clearThreadLocalTxn;

public class CountDownCommitBarrier_awaitOpenTest {
    private CountDownCommitBarrier barrier;

    @Before
    public void setUp() {
        clearThreadLocalTxn();
        clearCurrentThreadInterruptedStatus();
    }

    @After
    public void tearDown() {
        clearCurrentThreadInterruptedStatus();
    }

    @Test
    public void whenStartInterrupted_thenInterruptedException() {
        barrier = new CountDownCommitBarrier(1);

        Thread.currentThread().interrupt();

        try {
            barrier.awaitOpen();
            fail();
        } catch (InterruptedException expected) {
        }

        assertTrue(barrier.isClosed());
        assertEquals(0, barrier.getNumberWaiting());
    }

    @Test
    public void whenInterruptedWhileWaiting_thenInterruptedException() {
        barrier = new CountDownCommitBarrier(1);

        TestThread t = new TestThread() {
            @Override
            public void doRun() throws Exception {
                try {
                    barrier.awaitOpen();
                    fail();
                } catch (InterruptedException expected) {
                }
            }
        };
        t.start();

        sleepMs(500);
        t.interrupt();

        joinAll(t);
    }

    @Test
    public void whenAbortedWhileWaiting() {
        barrier = new CountDownCommitBarrier(1);

        TestThread t = new TestThread() {
            @Override
            public void doRun() throws Exception {
                barrier.awaitOpen();
            }
        };
        t.start();

        sleepMs(500);
        barrier.abort();

        joinAll(t);
    }

    @Test
    public void whenCommittedWhileWaiting() throws InterruptedException {
        barrier = new CountDownCommitBarrier(1);

        TestThread t = new TestThread() {
            @Override
            public void doRun() throws Exception {
                barrier.awaitOpen();
            }
        };
        t.start();

        sleepMs(500);
        barrier.countDown();
        joinAll(t);

        assertTrue(barrier.isCommitted());
    }

    @Test
    public void whenCommitted() throws InterruptedException {
        barrier = new CountDownCommitBarrier(0);

        barrier.awaitOpen();
        assertTrue(barrier.isCommitted());
        assertEquals(0, barrier.getNumberWaiting());
    }

    @Test
    public void whenAborted() throws InterruptedException {
        barrier = new CountDownCommitBarrier(1);
        barrier.abort();

        barrier.awaitOpen();
        assertTrue(barrier.isAborted());
        assertEquals(0, barrier.getNumberWaiting());
    }
}
