package utils

import (
	"encoding/base64"
	"fmt"
	"math/rand"
	"time"
)

func GenerateRandomString(length int, includeSpecialChar bool) string {

	rand.Seed(time.Now().UnixNano())
	letters := "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	specialChars := ".!@_#%^&*()-+"

	b := make([]rune, length)

	letterProbability := len(letters) * 100 / (len(letters) + len(specialChars))

	if includeSpecialChar {
		for i := range b {
			if rand.Intn(100) < letterProbability { // 概率选择字母
				b[i] = rune(letters[rand.Intn(len(letters))])
			} else { // 概率选择特殊字符
				b[i] = rune(specialChars[rand.Intn(len(specialChars))])
			}
		}
	} else {
		for i := range b {
			b[i] = rune(letters[rand.Intn(len(letters))])
		}
	}

	return string(b)
}

func ByteSizeToString(size uint64) string {
	const (
		B  = 1
		KB = 1024 * B
		MB = 1024 * KB
		GB = 1024 * MB
		TB = 1024 * GB
	)

	var unit string
	var value float64

	switch {
	case size >= TB:
		value = float64(size) / TB
		unit = "TB"
	case size >= GB:
		value = float64(size) / GB
		unit = "GB"
	case size >= MB:
		value = float64(size) / MB
		unit = "MB"
	case size >= KB:
		value = float64(size) / KB
		unit = "KB"
	default:
		value = float64(size)
		unit = "B"
	}

	return fmt.Sprintf("%.2f %s", value, unit)
}

func Base64Encode(content string) string {
	return base64.StdEncoding.EncodeToString([]byte(content))
}

func Base64Decode(content string) string {
	decodeString, err := base64.StdEncoding.DecodeString(content)
	if err != nil {
		log.ErrorF("Base64Decode error: %s", err.Error())
		return ""
	}
	return string(decodeString)
}
