package config

import (
	"os"
	"testing"
	"time"

	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

func TestInit(t *testing.T) {
	viper.SetConfigFile("./config_test.toml")
	viper.Set("baseSouthBoundType", 0)
	viper.Set("baseSouthBoundUUID", "bf8160d4-4659-4a1b-98fd-f409a04111eb")
	viper.Set("basePNDUUID", "bf8160d4-4659-4a1b-98fd-f409a04111ec")
	viper.Set("GOSDN_CHANGE_TIMEOUT", "10m")
	viper.Set("databaseConnection", "test@test:test")
}

func TestUseExistingConfig(t *testing.T) {
	TestInit(t)
	err := InitializeConfig()
	if err != nil {
		t.Error(err)
		return
	}

	if BasePndUUID.String() != "bf8160d4-4659-4a1b-98fd-f409a04111ec" {
		t.Fatalf("BasePndUUID.String() is not bf8160d4-4659-4a1b-98fd-f409a04111ec. got=%s",
			BasePndUUID.String())
	}

	testChangeTimeout, _ := time.ParseDuration("10m")
	defaultChangeTimeout := defaultTimeOutDuration10minutes
	if defaultChangeTimeout != testChangeTimeout {
		t.Fatalf("ChangeTimeout is not 10ms. got=%v",
			ChangeTimeout)
	}

	if os.Getenv("GOSDN_LOG") == "nolog" {
		if LogLevel != logrus.PanicLevel {
			t.Fatalf("LogLevel is not %v. got=%v",
				logrus.PanicLevel, LogLevel)
		}
	} else {
		if LogLevel != logrus.InfoLevel {
			t.Fatalf("LogLevel is not %v. got=%v",
				logrus.InfoLevel, LogLevel)
		}
	}

	if DatabaseConnection != "test@test:test" {
		t.Fatalf("DatabaseConnection is not test@test:test. got=%s",
			DatabaseConnection)
	}

	if UseDatabase() != true {
		t.Fatalf("DatabaseConnection is not set, but should not be used. got=%t",
			UseDatabase())
	}
}

func TestUseDatabase(t *testing.T) {
	viper.Set("databaseConnection", "")

	err := InitializeConfig()
	if err != nil {
		t.Error(err)
		return
	}

	if UseDatabase() != false {
		t.Fatalf("DatabaseConnection is not set and should not be used. got=%t",
			UseDatabase())
	}
}
