package util

import (
	"errors"

	"github.com/docker/go-units"
	"k8s.io/apimachinery/pkg/api/resource"

	"github.com/tidbcloud/infra-provider/pkg/consts"
)

func ParseDiskSizeAsGiB(s string) (int64, error) {
	if s == "" {
		return 0, errors.New("diskSize can't be empty")
	}
	r := s[len(s)-1]
	if r != 'B' && r != 'b' {
		s += "B"
	}
	size, err := units.RAMInBytes(s)
	if err != nil {
		return 0, err
	}
	return size / int64(units.GiB), nil
}

func MaxQuantity(a, b resource.Quantity) resource.Quantity {
	if a.Cmp(b) > 0 {
		return a
	}
	return b
}

func MaxQuantityStr(a, b string) (string, error) {
	qa, err := resource.ParseQuantity(a)
	if err != nil {
		return "", err
	}
	qb, err := resource.ParseQuantity(b)
	if err != nil {
		return "", err
	}
	max := MaxQuantity(qa, qb)
	return max.String(), nil
}

func StorageSizeGi2Quantity(sizeGi uint32) *resource.Quantity {
	sizeInt64 := int64(sizeGi)
	q := resource.NewQuantity(sizeInt64*consts.Gi, resource.BinarySI)
	_ = q.String()
	return q
}
