package devices

import (
	"testing"
	"time"

	"code.secondbit.org/uuid.hg"
)

func TestToMap(t *testing.T) {
	devices := []Device{
		{ID: uuid.NewID(), Name: "Test 1", Owner: uuid.NewID(), Type: TypeAndroidPhone, Created: time.Now(), LastSeen: time.Now(), PushToken: "test token"},
		{ID: uuid.NewID(), Name: "Test 2", Owner: uuid.NewID(), Type: TypeAndroidTablet, Created: time.Now(), LastSeen: time.Now(), PushToken: "test token"},
		{ID: uuid.NewID(), Name: "Test 3", Owner: uuid.NewID(), Type: TypeChromeExtension, Created: time.Now(), LastSeen: time.Now(), PushToken: "test token"},
	}
	expectation := map[string]Device{
		devices[0].ID.String(): devices[0],
		devices[1].ID.String(): devices[1],
		devices[2].ID.String(): devices[2],
	}
	result := ToMap(devices)

	if len(expectation) != len(result) {
		t.Errorf("Expected %d devices in map, got %d\n", len(expectation), len(result))
	}

	for _, device := range devices {
		ok, field, exp, res := compareDevices(expectation[device.ID.String()], result[device.ID.String()])
		if !ok {
			t.Errorf("Expected field %s of %s to be %v, got %v\n", field, device.Name, exp, res)
		}
	}
}

func TestToSlice(t *testing.T) {
	id1, id2, id3 := uuid.NewID(), uuid.NewID(), uuid.NewID()
	devices := map[string]Device{
		id1.String(): {ID: id1, Name: "Test 1", Owner: uuid.NewID(), Type: TypeAndroidPhone, Created: time.Now(), LastSeen: time.Now(), PushToken: "test token"},
		id2.String(): {ID: id2, Name: "Test 2", Owner: uuid.NewID(), Type: TypeAndroidTablet, Created: time.Now(), LastSeen: time.Now(), PushToken: "test token"},
		id3.String(): {ID: id3, Name: "Test 3", Owner: uuid.NewID(), Type: TypeChromeExtension, Created: time.Now(), LastSeen: time.Now(), PushToken: "test token"},
	}
	expectation := []Device{devices[id1.String()], devices[id2.String()], devices[id3.String()]}
	result := ToSlice(devices)

	if len(expectation) != len(result) {
		t.Errorf("Expected %d devices in slice, got %d\n", len(expectation), len(result))
	}

	for _, device := range expectation {
		var found bool
		for _, d := range result {
			if !d.ID.Equal(device.ID) {
				continue
			}
			found = true
			ok, field, exp, res := compareDevices(device, d)
			if !ok {
				t.Errorf("Expected field %s of %s to be %v, got %v\n", field, d.Name, exp, res)
			}
		}
		if !found {
			t.Errorf("Expected to find %s in result, did not\n", device.Name)
		}
	}
}
