package utils

import (
	"errors"
	"strconv"
	"strings"
)

func VersionToUint32(vs string) uint32 {
	varr := strings.Split(vs, ".")
	if len(varr) == 0 {
		return 0
	}

	var uintversion uint32 = 0
	for _, v := range varr {
		if iv, err := strconv.Atoi(v); err == nil {
			uintversion = (uintversion << 8) + uint32(iv)
		}
	}
	return uintversion
}

// v1>v2 return true
func VersionNewer(version1, version2 string) (bool, error) {
	v1arr := strings.Split(version1, ".")
	v2arr := strings.Split(version2, ".")
	if len(v1arr) == 0 || len(v2arr) == 0 {
		return false, errors.New("string is null")
	}

	num := 0
	if len(v1arr) < len(v2arr) {
		num = len(v1arr)
	} else {
		num = len(v2arr)
	}

	for i := 0; i < num; i++ {
		v1, _ := strconv.Atoi(v1arr[i])
		v2, _ := strconv.Atoi(v2arr[i])
		switch {
		case v1 > v2:
			return true, nil
		case v1 < v2:
			return false, nil
		}
	}

	return false, nil
}
