package service

import (
	"fmt"
	"runtime"
	"strings"

	"be.ems/src/framework/cmd"
	"be.ems/src/framework/config"
)

// GetOMCYaml 获取OMC网元配置文件 /usr/local/etc/omc/omc.yaml
func (r NeConfig) GetOMCYaml(paramName string) []map[string]any {
	if paramName == "trace" {
		traceData := config.Get("trace").(map[string]any)
		return []map[string]any{traceData}
	}
	return []map[string]any{}
}

// ModifyOMCYaml 修改OMC网元配置文件 /usr/local/etc/omc/omc.yaml
func (r NeConfig) ModifyOMCYaml(paramName, loc string, paramData any) error {
	neConfig := r.SelectNeConfigByNeTypeAndParamName("OMC", paramName)
	if neConfig.ParamType == "list" {
		if paramName == "trace" {
			configPath := fmt.Sprint(config.Get("config")) // 获取配置文件路径
			paramDataMap := paramData.(map[string]any)
			for k, v := range paramDataMap {
				config.Set(fmt.Sprintf("trace.%s", strings.ToLower(k)), v)
				if runtime.GOOS == "windows" {
					continue // Windows系统不支持sed命令
				}
				// 修改参数较少，直接命令改文件内容
				if k == "enabled" {
					// sed 's/enabled: \(true\|false\) # trace enabled/enabled: true # trace enabled/' /usr/local/etc/omc/omc.yaml
					cmd.Execf("sed -i 's/enabled: \\(true\\|false\\) # trace enabled/enabled: %v # trace enabled/' %s", v, configPath)
				}
				if k == "host" {
					// sed 's/host: ".*" # trace host/host: "127.2.2.2" # trace host/' /usr/local/etc/omc/omc.yaml
					cmd.Execf("sed -i 's/host: \".*\" # trace host/host: \"%v\" # trace host/' %s", v, configPath)
				}
				if k == "port" {
					// sed 's/port: [0-9]\+ # trace port/port: 6964 # trace port/' /usr/local/etc/omc/omc.yaml
					cmd.Execf("sed -i 's/port: [0-9]\\+ # trace port/port: %v # trace port/' %s", v, configPath)
				}
			}
			// 重开跟踪任务信令数据通道UDP
			// service.NewTraceTask.CreateUDP(true) 方法导致循环引用，抛给上层调用
			return nil
		}
	}
	if neConfig.ParamType == "array" {
		// TODO
	}
	return fmt.Errorf("not found method paramName")
}
