package autoconfig

import (
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"gopkg.in/yaml.v2"
)

type ConfigServer struct {
	Name      string
	Host      string `yaml:"Host"`
	Port      int    `yaml:"Port"`
	ReplicaId uint64 `yaml:"ReplicaId"`
}

func AutoGetAllServerConfig() []*ConfigServer {
	var servers []*ConfigServer
	etcPath := AutoGetEtcYaml()
	err := filepath.Walk(*etcPath+"/server", func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		// Skip if not a file or not a yaml file
		if info.IsDir() || filepath.Ext(path) != ".yaml" {
			return nil
		}

		// Read file
		data, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}

		// Unmarshal the yaml content
		var server ConfigServer
		err = yaml.Unmarshal(data, &server)
		if err != nil {
			return err
		}
		dirs := strings.Split(path, "/")

		server.Name = dirs[len(dirs)-3]
		// Add the server to the list
		servers = append(servers, &server)
		return nil
	})

	if err != nil {
		panic("Error: " + err.Error())
	}
	return servers
}

func AutoGetEtcYaml() *string {
	var currentFilePath string
	var ok bool

	_, currentFilePath, _, ok = runtime.Caller(1)
	if !ok {
		panic("Error: Unable to get the current file path.")
	}

	dirs := strings.Split(currentFilePath, "/")
	dirs = dirs[0 : len(dirs)-1]

	for len(dirs) != 0 {
		curPath := strings.Join(dirs, "/")

		dirs = dirs[0 : len(dirs)-1]

		// 列出所有 curPath 下的文件夹
		files, err := ioutil.ReadDir(curPath)
		if err != nil {
			log.Println(err)
			continue
		}

		// 查找每个文件夹下是否存在 server
		for _, file := range files {
			if file.Name() == "server" {
				return &curPath
			}
		}
	}

	return nil
}