package oobs

import (
	"strings"
	"time"
)

func nowUTC(nowFn func() time.Time) time.Time {
	if nowFn == nil {
		return time.Now().UTC()
	}
	return nowFn().UTC()
}

func cloneStringMap(src map[string]string) map[string]string {
	if len(src) == 0 {
		return nil
	}
	out := make(map[string]string, len(src))
	for key, value := range src {
		out[strings.TrimSpace(key)] = strings.TrimSpace(value)
	}
	return out
}

func trimStringMap(src map[string]string) map[string]string {
	if len(src) == 0 {
		return nil
	}
	out := make(map[string]string, len(src))
	for key, value := range src {
		k := strings.TrimSpace(key)
		v := strings.TrimSpace(value)
		if k == "" && v == "" {
			continue
		}
		out[k] = v
	}
	if len(out) == 0 {
		return nil
	}
	return out
}

func mergeMaps(left map[string]string, right map[string]string) map[string]string {
	if len(left) == 0 && len(right) == 0 {
		return nil
	}
	out := make(map[string]string, len(left)+len(right))
	for key, value := range left {
		out[key] = value
	}
	for key, value := range right {
		out[key] = value
	}
	if len(out) == 0 {
		return nil
	}
	return out
}

func stepAttemptKey(paymentRef string, stepRef string, attempt uint32) string {
	return paymentRef + "|" + stepRef + "|" + uint32String(attempt)
}

func uint32String(v uint32) string {
	if v == 0 {
		return "0"
	}
	var buf [10]byte
	i := len(buf)
	for v > 0 {
		i--
		buf[i] = byte('0' + v%10)
		v /= 10
	}
	return string(buf[i:])
}

func reverseEntries(items []TimelineEntry) []TimelineEntry {
	if len(items) <= 1 {
		return items
	}
	out := make([]TimelineEntry, 0, len(items))
	for i := len(items) - 1; i >= 0; i-- {
		out = append(out, items[i])
	}
	return out
}
