package queues

import (
	"context"
	"encoding/json"
	"fmt"
	"gitee.ltd/lxh/logger/log"
	"github.com/spf13/cast"
	"os"
	"strconv"
	"wireguard-dashboard/client"
	"wireguard-dashboard/component"
	"wireguard-dashboard/constant"
	"wireguard-dashboard/model/template_data"
	"wireguard-dashboard/repository"
)

// asyncWireguardConfigFile
// @description: 同步配置文件
func asyncWireguardConfigFile() {
	for {
		result, err := client.Redis.BRPop(context.Background(), 0, fmt.Sprintf("%s", constant.SyncWgConfigFile)).Result()
		if err != nil {
			//log.Errorf("获取任务失败")
			continue
		}

		serverId := result[1]
		if serverId == "" {
			serverInfo, err := repository.Server().GetServer()
			if err != nil {
				log.Errorf("没有找到服务端: %v", err.Error())
				continue
			}
			serverId = serverInfo.Id
		}

		// 使用serverId获取服务信息
		serverEnt, err := repository.Server().GetServerWithClient(serverId)
		if err != nil {
			log.Errorf("获取服务端信息失败: %s", err.Error())
			continue
		}

		// 获取服务端全局配置
		globalSetting, err := repository.System().GetServerSetting()
		if err != nil {
			log.Errorf("获取服务端配置失败: %s", err.Error())
			continue
		}

		if globalSetting.ConfigFilePath == "" {
			globalSetting.ConfigFilePath = "/etc/wireguard/wg0.conf"
		}

		// 获取模板文件和输出目录
		var templatePath, outFilePath string
		if os.Getenv("GIN_MODE") != "release" {
			templatePath = "E:\\Workspace\\Go\\wireguard-dashboard\\template\\wg.conf"
			outFilePath = "E:\\Workspace\\Go\\wireguard-dashboard\\wg0.conf"
		} else {
			templatePath = "./template/wg.conf"
			outFilePath = globalSetting.ConfigFilePath
		}

		// 组装数据
		renderServer := template_data.Server{
			Address:    serverEnt.IpScope,
			ListenPort: serverEnt.ListenPort,
			PrivateKey: serverEnt.PrivateKey,
			MTU:        globalSetting.MTU,
			PostUp:     serverEnt.PostUpScript,
			PreDown:    serverEnt.PreDownScript,
			PostDown:   serverEnt.PostDownScript,
			Table:      globalSetting.Table,
		}

		// 客户端数据
		var renderClients []template_data.Client
		for _, v := range serverEnt.Clients {
			var clientKey template_data.Keys
			_ = json.Unmarshal([]byte(v.Keys), &clientKey)
			var createUserName string
			if v.User != nil {
				createUserName = v.User.Name
			}
			renderClients = append(renderClients, template_data.Client{
				ID:                  v.Id,
				Name:                v.Name,
				Email:               v.Email,
				PublicKey:           clientKey.PublicKey,
				PresharedKey:        clientKey.PresharedKey,
				AllowedIPS:          v.AllowedIps,
				PersistentKeepalive: strconv.Itoa(globalSetting.PersistentKeepalive),
				Endpoint:            v.Endpoint,
				CreatedAt:           v.CreatedAt.String(),
				UpdatedAt:           v.UpdatedAt.String(),
				CreateUser:          createUserName,
				Enabled:             cast.ToBool(v.Enabled),
			})
		}

		renderData := map[string]any{
			"Server":  renderServer,
			"Clients": renderClients,
		}

		err = component.Wireguard().Apply(templatePath, outFilePath, renderData)
		if err != nil {
			log.Errorf("同步配置文件失败: %s", err.Error())
			continue
		}

	}
}
