package syncext

import (
	"testing"
	"time"
)

func TestTimeoutReadBuffered(t *testing.T) {
	c := make(chan int, 1)

	go func() {
		time.Sleep(200 * time.Millisecond)
		c <- 112
	}()

	_, ok := ReadChannelWithTimeout(c, 100*time.Millisecond)

	if ok {
		t.Error("Read success, but should timeout")
	}
}

func TestTimeoutReadBigBuffered(t *testing.T) {
	c := make(chan int, 128)

	go func() {
		time.Sleep(200 * time.Millisecond)
		c <- 112
	}()

	_, ok := ReadChannelWithTimeout(c, 100*time.Millisecond)

	if ok {
		t.Error("Read success, but should timeout")
	}
}

func TestTimeoutReadUnbuffered(t *testing.T) {
	c := make(chan int)

	go func() {
		time.Sleep(200 * time.Millisecond)
		c <- 112
	}()

	_, ok := ReadChannelWithTimeout(c, 100*time.Millisecond)

	if ok {
		t.Error("Read success, but should timeout")
	}
}

func TestNoTimeoutAfterStartReadBuffered(t *testing.T) {
	c := make(chan int, 1)

	go func() {
		time.Sleep(10 * time.Millisecond)
		c <- 112
	}()

	_, ok := ReadChannelWithTimeout(c, 100*time.Millisecond)

	if !ok {
		t.Error("Read timeout, but should have succeeded")
	}
}

func TestNoTimeoutAfterStartReadBigBuffered(t *testing.T) {
	c := make(chan int, 128)

	go func() {
		time.Sleep(10 * time.Millisecond)
		c <- 112
	}()

	_, ok := ReadChannelWithTimeout(c, 100*time.Millisecond)

	if !ok {
		t.Error("Read timeout, but should have succeeded")
	}
}

func TestNoTimeoutAfterStartReadUnbuffered(t *testing.T) {
	c := make(chan int)

	go func() {
		time.Sleep(10 * time.Millisecond)
		c <- 112
	}()

	_, ok := ReadChannelWithTimeout(c, 100*time.Millisecond)

	if !ok {
		t.Error("Read timeout, but should have succeeded")
	}

}

func TestNoTimeoutBeforeStartReadBuffered(t *testing.T) {
	c := make(chan int, 1)

	c <- 112

	_, ok := ReadChannelWithTimeout(c, 10*time.Millisecond)

	if !ok {
		t.Error("Read timeout, but should have succeeded")
	}
}

func TestNoTimeoutBeforeStartReadBigBuffered(t *testing.T) {
	c := make(chan int, 128)

	c <- 112

	_, ok := ReadChannelWithTimeout(c, 10*time.Millisecond)

	if !ok {
		t.Error("Read timeout, but should have succeeded")
	}
}
