package com.njcn.gather.detection.util.socket;

import com.njcn.gather.script.pojo.po.SourceIssue;
import org.junit.After;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

public class FormalTestManagerPauseTest {

    @After
    public void tearDown() {
        FormalTestManager.clearFormalRuntime();
        SocketManager.clearFormalRuntime();
    }

    @Test
    public void requestWaitPause_keepsPauseDeferredUntilCurrentItemFinishes() {
        FormalTestManager.requestWaitPause();

        assertTrue(FormalTestManager.stopFlag);
        assertFalse(FormalTestManager.hasStopFlag);
        assertTrue(FormalTestManager.isWaitCurrentItemPause());
        assertFalse(FormalTestManager.isImmediatePause());
    }

    @Test
    public void requestImmediatePause_entersPausedStateImmediately() {
        FormalTestManager.requestImmediatePause();

        assertTrue(FormalTestManager.stopFlag);
        assertTrue(FormalTestManager.hasStopFlag);
        assertFalse(FormalTestManager.isWaitCurrentItemPause());
        assertTrue(FormalTestManager.isImmediatePause());
        assertEquals(Integer.valueOf(0), FormalTestManager.stopTime);
    }

    @Test
    public void ensureFirst_keepsCurrentIssueAtQueueHead() {
        SourceIssue first = issue(1, "V");
        SourceIssue second = issue(2, "I");
        SocketManager.addSourceList(new ArrayList<>(Arrays.asList(second)));

        SocketManager.ensureFirst(first);

        assertSame(first, SocketManager.getSourceList().get(0));
        assertSame(second, SocketManager.getSourceList().get(1));
    }

    @Test
    public void ensureFirst_doesNotDuplicateExistingHead() {
        SourceIssue first = issue(1, "V");
        SocketManager.addSourceList(new ArrayList<>(Arrays.asList(first)));

        SocketManager.ensureFirst(first);

        assertEquals(1, SocketManager.getSourceList().size());
        assertSame(first, SocketManager.getSourceList().get(0));
    }

    private SourceIssue issue(Integer index, String type) {
        SourceIssue issue = new SourceIssue();
        issue.setIndex(index);
        issue.setType(type);
        issue.setDesc(type + " item");
        return issue;
    }
}
