package ip

import (
	"errors"
	"net"
	"reflect"
	"testing"

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

func defaultCallback(t *testing.T, expected_name string, ip net.IP, err error) CacheDefaultCallback {
	return func(name string) (net.IP, error) {
		assert.Equal(t, expected_name, name)
		return ip, err
	}
}

func dontCallDefaultCallback(t *testing.T) CacheDefaultCallback {
	return func(name string) (net.IP, error) {
		t.Error("Should not have been called")
		return nil, nil
	}
}

func TestCache_Get(t *testing.T) {
	tests := []struct {
		name    string
		c       *Cache
		iface   string
		want    net.IP
		wantErr bool
	}{
		{"Exists in cache", &Cache{items: map[string]net.IP{"eth0": net.IPv4(10, 4, 0, 1)}}, "eth0", net.IPv4(10, 4, 0, 1), false},
		{"Did not exist in cache", &Cache{items: map[string]net.IP{}}, "eth0", nil, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := tt.c.Get(tt.iface)
			if (err != nil) != tt.wantErr {
				t.Errorf("Cache.Get() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("Cache.Get() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestCache_GetWithDefault(t *testing.T) {
	tests := []struct {
		name    string
		c       *Cache
		def     CacheDefaultCallback
		iface   string
		want    net.IP
		wantErr bool
	}{
		{"Exists in cache", &Cache{items: map[string]net.IP{"eth0": net.IPv4(10, 4, 0, 1)}}, dontCallDefaultCallback(t), "eth0", net.IPv4(10, 4, 0, 1), false},
		{"Did not exists in cache", NewCache(), defaultCallback(t, "eth1", net.IPv4(192, 172, 44, 25), nil), "eth1", net.IPv4(192, 172, 44, 25), false},
		{"Callback returns error", NewCache(), defaultCallback(t, "eth1", nil, errors.New("some error")), "eth1", nil, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := tt.c.GetWithDefault(tt.iface, tt.def)
			if (err != nil) != tt.wantErr {
				t.Errorf("Cache.Get() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("Cache.Get() = %v, want %v", got, tt.want)
			}
		})
	}
}
