package main

import (
	"errors"
	"io/ioutil"
	"path"
	"testing"

	"github.com/spf13/viper"
)

// TestLoadServiceFileAdded tests that loading a service file adds the service to the config.
func TestLoadServiceFileAdded(t *testing.T) {
	c := viper.New()
	srvDir, err := ioutil.TempDir("", "services.d")
	if err != nil {
		t.Fatal(err)
	}
	if err := ioutil.WriteFile(path.Join(srvDir, "test.service"), []byte("[services.a]\n"), 0644); err != nil {
		t.Fatal(err)
	}
	c.Set("services_directory", srvDir)
	if err := loadServices(c); err != nil {
		t.Fatal(err)
	}
	if !c.IsSet("services.a") {
		t.Error(errors.New("a is not set in services"))
	}
}

// TestLoadServiceFileAdded tests that loading a service file does not overwrite any services already defined in the config.
func TestLoadConfigServiceNotClobbered(t *testing.T) {
	c := viper.New()
	c.Set("services.b", &necroServiceConfigurationEntry{})
	srvDir, err := ioutil.TempDir("", "services.d")
	if err != nil {
		t.Fatal(err)
	}
	if err := ioutil.WriteFile(path.Join(srvDir, "test.service"), []byte("[services.a]\n"), 0644); err != nil {
		t.Fatal(err)
	}
	c.Set("services_directory", srvDir)
	if err := loadServices(c); err != nil {
		t.Fatal(err)
	}
	if !c.IsSet("services.b") {
		t.Error(errors.New("b is not set in services"))
	}
}

// TestLoadServiceFileAdded tests that loading a service file does not overwrite any other configuration values.
func TestLoadServiceFileOnlyLoadsServices(t *testing.T) {
	c := viper.New()
	c.Set("services.b", &necroServiceConfigurationEntry{})
	srvDir, err := ioutil.TempDir("", "services.d")
	if err != nil {
		t.Fatal(err)
	}
	if err := ioutil.WriteFile(path.Join(srvDir, "test.service"), []byte("key=\"value\""), 0644); err != nil {
		t.Fatal(err)
	}
	c.Set("services_directory", srvDir)
	if err := loadServices(c); err != nil {
		t.Fatal(err)
	}
	if c.IsSet("key") {
		t.Error(errors.New("key should not be set"))
	}
}
