package xray

import (
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"

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

func TestEnvironmentName(t *testing.T) {
	os.Setenv("XRAY_TRACING_NAME", "EnvName")
	resetConfig()

	h := Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	r, _ := http.NewRequest("GET", "http://10.0.0.1/", nil)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)

	seg, e := <-testDaemon.Recv, <-testDaemon.Err
	assert.Nil(t, e)

	os.Unsetenv("XRAY_TRACING_NAME")
	assert.Equal(t, "EnvName", seg.Name)
}

func TestEnvironmentDefaultName(t *testing.T) {
	os.Setenv("XRAY_TRACING_DEFAULT_NAME", "DefaultEnvName")
	resetConfig()

	h := Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	r, _ := http.NewRequest("GET", "http://10.0.0.1/", nil)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)

	seg, e := <-testDaemon.Recv, <-testDaemon.Err
	assert.Nil(t, e)

	os.Unsetenv("XRAY_TRACING_DEFAULT_NAME")

	assert.Equal(t, "DefaultEnvName", seg.Name)
}

func TestConfigName(t *testing.T) {
	resetConfig()
	conf := Config{
		Name:        "ConfigName",
		DefaultName: "DefaultConfigName",
	}

	Configure(conf)

	h := Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	r, _ := http.NewRequest("GET", "http://10.0.0.1/", nil)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)

	seg, e := <-testDaemon.Recv, <-testDaemon.Err
	assert.Nil(t, e)

	assert.Equal(t, "ConfigName", seg.Name)
}

func TestDefaultConfigName(t *testing.T) {
	resetConfig()
	conf := Config{
		DefaultName: "DefaultConfigName",
	}

	Configure(conf)

	h := Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	r, _ := http.NewRequest("GET", "http://10.0.0.1/", nil)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)

	seg, e := <-testDaemon.Recv, <-testDaemon.Err
	assert.Nil(t, e)

	assert.Equal(t, "DefaultConfigName", seg.Name)
}

func TestWorkingDaemonAddr(t *testing.T) {
	tempAddr := &net.UDPAddr{
		IP:   net.IPv4(127, 0, 0, 1),
		Port: 2001,
	}

	conn, err := net.ListenUDP("udp", tempAddr)
	assert.Nil(t, err)
	tempDaemon := &testdaemon{
		Connection: conn,
	}
	go tempDaemon.Run()

	conf := Config{
		DaemonAddr: "127.0.0.1:2001",
	}

	err = Configure(conf)

	tempDaemon.Done = true
	assert.Empty(t, err)
	resetConfig()
}

func TestFailingDaemonAddr(t *testing.T) {
	conf := Config{
		DaemonAddr: "fakeHost:2017",
	}

	err := Configure(conf)

	assert.Error(t, err)
	resetConfig()
}
