package tests

import (
	"flag"
	"fmt"
	"os"
	"path"
	"runtime"
	"testing"
	"time"

	"github.com/pingcap/dbaas/billing2/model/costexplorer"

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

func TestInit(t *testing.T) {
	path, _ := os.MkdirTemp("", "billing")
	_ = flag.Set("conf", path)
	conf := `
mysql-host=test-mysql-host
`
	_ = os.WriteFile(path+"/config.properties", []byte(conf), os.ModePerm)
	defer deferRemove(path, os.RemoveAll)
	defer deferRemove(path+"/config.properties", os.RemoveAll)
	err := config.InitLocal()
	assert.Nil(t, err)
	assert.Equal(t, "test-mysql-host", config.Get().GetString(config.MySQLHost))
	assert.Equal(t, "root", config.Get().GetString(config.MySQLUser))
	conf = `
mysql-host=test-mysql-host2
`
	_ = os.WriteFile(path+"/config.properties", []byte(conf), os.ModePerm)
	time.Sleep(time.Second)
	assert.Equal(t, "test-mysql-host2", config.Get().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)
	config.Get().AddConfigPath(path.Join(path.Dir(codeFile), "../"))
	config.Get().SetDefault(config.Project, "nightly-ms")
	config.Get().Set(config.EnableRemoteConfig, true)
	err := config.Init()
	assert.NoError(err)
	assert.True(config.Get().GetBool("enable-remote"))
	appUsageUnitsMap := config.Get().GetStringMapString("eda" + costexplorer.AppCfgSuffix)

	fmt.Println(appUsageUnitsMap)
	//config.Get().SetDefault("enable-remote", false)
	//assert.True(config.Get().GetBool("enable-remote"))
	//config.Get().Set("enable-remote", false)
	//assert.False(config.Get().GetBool("enable-remote"))
}

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