package i18n

import (
	"fmt"
	"regexp"
	"strings"

	"be.ems/src/framework/constants"
	"be.ems/src/framework/database/redis"
)

// TFindKeyPrefix 翻译值查找键 值前缀匹配
func TFindKeyPrefix(language, keyPrefix, value string) string {
	key := value
	if key == "" {
		return key
	}

	langKey := constants.CACHE_I18N + ":" + keyPrefix + "*"
	prefixKeys, err := redis.GetKeys("", langKey)
	if err != nil {
		return key
	}
	mkv, err := redis.GetHashBatch("", prefixKeys)
	if err != nil {
		return key
	}

	for k, m := range mkv {
		// 跳过-号数据 i18n:menu.system.menu

		if v, ok := m[language]; ok {
			if strings.HasPrefix(v, value) {
				key = k[len(constants.CACHE_I18N)+1:]
				break
			}
		}
	}
	return key
}

// TKey 翻译键
// language: zh-中文 en-英文
func TKey(language, key string) string {
	value := key
	if key == "" {
		return value
	}

	langKey := constants.CACHE_I18N + ":" + key
	output, err := redis.GetHash("", langKey, language)
	if err != nil {
		return value
	}
	return output
}

// TTemplate 翻译模板字符串
func TTemplate(language, key string, params map[string]any) string {
	templateString := TKey(language, key)

	re := regexp.MustCompile("{(.*?)}")
	result := re.ReplaceAllStringFunc(templateString, func(match string) string {
		key := match[1 : len(match)-1]
		if val, ok := params[key]; ok {
			return fmt.Sprint(val)
		}
		return match
	})

	return result
}
