package component

import (
	"gitee.ltd/lxh/logger/log"
	"gopkg.in/fsnotify.v1"
	"wireguard-dashboard/command"
	"wireguard-dashboard/config"
	"wireguard-dashboard/utils"
)

type wireguard struct{}

func Wireguard() wireguard {
	return wireguard{}
}

// Apply
// @description: 应用配置
// @receiver wireguard
// @return err
func (w wireguard) Apply(templateFilePath, configFilePath string, data any) (err error) {

	parseTemplate, err := utils.Template().Parse(templateFilePath)
	if err != nil {
		log.Errorf("解析模板信息失败")
		return err
	}

	err = utils.Template().Execute(parseTemplate, data, configFilePath)
	if err != nil {
		log.Errorf("应用配置失败: %v", err.Error())
		return err
	}

	// 判断服务端重启规则
	switch config.Config.Wireguard.ListenConfig {
	case "auto":
		w.watchListConfig(configFilePath)
	}

	return nil
}

// watchListConfig
// @description: 监听配置文件变化
// @receiver wireguard
// @return err
func (wireguard) watchListConfig(filePath string) {
	go func() {
		watcher, err := fsnotify.NewWatcher()
		if err != nil {
			log.Errorf("创建文件监控失败: %v", err.Error())
			return
		}

		defer watcher.Close()
		done := make(chan bool)

		go func() {
			for {
				select {
				case event, ok := <-watcher.Events:
					if !ok {
						return
					}

					if event.Op == fsnotify.Write {
						command.RestartWireguard(true)
					}

					// 打印监听事件
					log.Errorf("监听事件是：%s", event.String())
				case _, ok := <-watcher.Errors:
					if !ok {
						return
					}
				}
			}
		}()

		if err = watcher.Add(filePath); err != nil {
			log.Errorf("添加[%s]监听失败: %v", filePath, err.Error())
			return
		}
		<-done
	}()
}
