package com.atlassian.bitbucket.mesh.git.hook;

import com.google.common.collect.ImmutableList;
import com.google.common.io.LineProcessor;
import org.junit.Test;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.*;

public class ByteStringHookStdinTest {

    @Test
    public void testReadAndRelease() throws Exception {
        ByteStringHookStdin stdin = ByteStringHookStdin.of("This is a test");
        assertEquals("This is a test", stdin.read());
        assertFalse(stdin.isReleased());

        stdin.release();
        assertTrue(stdin.isReleased());

        IllegalStateException thrown = assertThrows(IllegalStateException.class, stdin::open);
        assertThat(thrown.getMessage(), containsString("already been released"));
    }

    @Test
    public void testReadLines() throws Exception {
        ByteStringHookStdin stdin = ByteStringHookStdin.of("One\nTwo\nThree");
        assertEquals(13L, stdin.size());

        List<String> actual = stdin.readLines(new LineProcessor<List<String>>() {

            private final List<String> lines = new ArrayList<>();

            @Override
            public List<String> getResult() {
                return lines;
            }

            @Override
            public boolean processLine(@Nonnull String line) {
                lines.add(line);
                return true;
            }
        });
        assertNotNull(actual);
        assertEquals(ImmutableList.of("One", "Two", "Three"), ImmutableList.copyOf(actual));
    }
}