package utils

import (
	"context"
	"encoding/base64"
	"fmt"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/frame/g"
	"os"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"time"
)

var (
	pid           = os.Getpid()
	gormSourceDir string
)

func init() {
	_, file, _, _ := runtime.Caller(0)
	gormSourceDir = regexp.MustCompile(`utils.utils\.go`).ReplaceAllString(file, "")
}

// NewTraceID 创建追踪ID
func NewTraceID() string {
	return fmt.Sprintf("trace-id-%d-%s",
		pid,
		time.Now().Format("2006.01.02.15.04.05.999999"))
}

func FileWithLineNum() string {
	for i := 2; i < 15; i++ {
		_, file, line, ok := runtime.Caller(i)

		if ok && (!strings.HasPrefix(file, gormSourceDir) || strings.HasSuffix(file, "_test.go")) {
			return file + ":" + strconv.FormatInt(int64(line), 10)
		}
	}
	return ""
}

// Base64Encode Base64加密
func Base64Encode(org string) string {
	return base64.StdEncoding.EncodeToString([]byte(org))
}

func GetConfig(key string) *gvar.Var {
	ret, err := g.Cfg().Get(context.Background(), key)
	if err != nil {

	}
	return ret
}

func EscapeQuotes(s string) string {
	return strings.ReplaceAll(s, `"`, `\"`)
}
