package discovery

import (
	"testing"
	"time"

	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

func TestDiscovery(t *testing.T) {
	config, err := clientcmd.BuildConfigFromFlags("", "/home/mats/.kube/config")
	if err != nil {
		t.Errorf("Error building config: %v", err)
	}
	client, err := kubernetes.NewForConfig(config)
	if err != nil {
		t.Errorf("Error creating client: %v", err)
	}
	d := NewK8sDiscovery(client)
	res, err := d.DiscoverInNamespace("")
	if err != nil {
		t.Errorf("Error discovering: %v", err)
	}
	if len(res) == 0 {
		t.Errorf("Expected at least one host, got none")
	}
}

func TestWatch(t *testing.T) {
	config, err := clientcmd.BuildConfigFromFlags("", "/home/mats/.kube/config")
	if err != nil {
		t.Errorf("Error building config: %v", err)
	}
	client, err := kubernetes.NewForConfig(config)
	if err != nil {
		t.Errorf("Error creating client: %v", err)
	}
	d := NewK8sDiscovery(client)
	ch, err := d.Watch()
	if err != nil {
		t.Errorf("Error watching: %v", err)
	}

	select {
	case m := <-ch:
		t.Logf("Received watch %v", m)
	case <-time.After(5 * time.Second):
		t.Errorf("Timeout waiting for watch")
	}
}
