package ping

import (
	"errors"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestSystemPing(t *testing.T) {
	type testCase struct {
		// constructors
		address string

		// results
		expectedMatch float64
		err           error
	}

	t.Run("ping localhost (via 127.0.0.1)", func(t *testing.T) {
		tests := []testCase{{"127.0.0.1", 0, nil}}

		for _, test := range tests {
			result, err := runPing(test.address)

			// result data prep
			lines := strings.Split(strings.ReplaceAll(string(*result), "\r\n", "\n"), "\n")
			var has_addr bool
			for _, line := range lines {
				if strings.Contains(line, "127.0.0.1") {
					has_addr = true
				}
			}

			// assertions
			assert.NoError(t, err)
			assert.True(t, has_addr)
		}
	})
}

func TestSplitBytes(t *testing.T) {
	type testCase struct {
		// test data
		bytes *[]byte

		// expected results
		lines []string
	}
	t.Run("test bytes to lines", func(t *testing.T) {
		var tests []testCase
		// init tests
		for range 5 {
			bytes, _ := runPing("127.0.0.1")
			lines := strings.Split(strings.ReplaceAll(string(*bytes), "\r\n", "\n"), "\n")
			tests = append(tests, testCase{bytes: bytes, lines: lines})
		}

		// run tests
		for _, test := range tests {
			lines := splitBytesToLines(test.bytes)

			assert.Equal(t, lines, test.lines)
		}
	})
}

func TestPing(t *testing.T) {
	type testCase struct {
		address string

		delay float64
		err   error
	}
	t.Run("test golang ping interface", func(t *testing.T) {
		var tests []testCase
		// init tests
		for range 5 {
			tests = append(tests, testCase{
				address: "127.0.0.1",
				delay:   0,
				err:     nil,
			})
		}
		tests = append(tests, testCase{address: "willneverresolveever", delay: -1, err: errors.New("test failure")})

		for _, test := range tests {
			delay, err := Ping(test.address)
			assert.GreaterOrEqual(t, delay, test.delay)
			if test.err != nil {
				assert.Error(t, err)
				assert.Equal(t, delay, test.delay)
			} else {
				assert.NoError(t, err)
			}
		}
	})
}
