package tests

import (
	"flag"
	"io/ioutil"
	"os"
	"path"
	"runtime"
	"testing"
	"time"

	"github.com/pingcap/dbaas/billing2/config"
	"github.com/pingcap/log"
	"github.com/spf13/viper"
	"github.com/stretchr/testify/assert"
	"go.uber.org/zap"
)

func TestInit(t *testing.T) {
	path, _ := ioutil.TempDir("", "billing")
	_ = flag.Set("conf", path)
	conf := `
mysql-host=test-mysql-host
`
	_ = ioutil.WriteFile(path+"/config.properties", []byte(conf), os.ModePerm)
	defer deferRemove(path, os.Remove)
	defer deferRemove(path+"/config.properties", os.Remove)
	err := config.InitLocal()
	assert.Nil(t, err)
	assert.Equal(t, "test-mysql-host", viper.GetString(config.MySQLHost))
	assert.Equal(t, "root", viper.GetString(config.MySQLUser))
	conf = `
mysql-host=test-mysql-host2
`
	_ = ioutil.WriteFile(path+"/config.properties", []byte(conf), os.ModePerm)
	time.Sleep(time.Second)
	assert.Equal(t, "test-mysql-host2", viper.GetString(config.MySQLHost))
}

func deferRemove(arg string, f func(string) error) {
	if err := f(arg); err != nil {
		log.Warn("failed to call defer func", zap.Error(err))
	}
}

func TestRemoteConfig(t *testing.T) {
	t.Skip("can not run it in ut")
	assert := assert.New(t)
	_, codeFile, _, _ := runtime.Caller(0)
	viper.AddConfigPath(path.Join(path.Dir(codeFile), "../"))
	viper.SetDefault(config.Project, "nightly")
	err := config.Init()
	assert.NoError(err)
	assert.True(viper.GetBool("enable-remote"))
	viper.SetDefault("enable-remote", false)
	assert.True(viper.GetBool("enable-remote"))
	viper.Set("enable-remote", false)
	assert.False(viper.GetBool("enable-remote"))
}

func TestConfigNotExistInRemote(t *testing.T) {
	assert := assert.New(t)
	_, codeFile, _, _ := runtime.Caller(0)
	viper.Reset()
	viper.AddConfigPath(path.Join(path.Dir(codeFile), "../"))
	err := config.Init()
	assert.NoError(err)
	viper.SetDefault("test", "test")
	assert.Equal(viper.Get("test"), "test")
}
