package hexadecimal

import (
	"errors"
	"strings"
)

func ParseHex(in string) (int64, error) {
	return convertNumStringBase(in, int64(16))
}

func HandleErrors(in []string) []string {
	var ret []string
	for i := range in {
		errStr := "none"
		_, err := convertNumStringBase(in[i], 16)
		if err != nil {
			errStr = err.Error()
		}
		ret = append(ret, errStr)
	}
	return ret
}

// convertNumStringBase takes a numeric string and the base of that string
// and returns an int64 of the decimal representation
func convertNumStringBase(in string, base int64) (int64, error) {
	if in == "" {
		return 0, errors.New("syntax")
	}
	in = strings.ToLower(in)
	var a, n int64
	for i := range in {
		n *= base
		switch {
		case in[i] >= '0' && in[i] <= '9':
			a = int64(in[i] - '0')
		case in[i] >= 'a' && in[i] <= 'f':
			a = int64(in[i]-'a') + 10
		default:
			return 0, errors.New("syntax")
		}
		if a > base {
			return 0, errors.New("syntax")
		}
		n += a

		if n <= 0 && in[0] != '0' {
			return 0, errors.New("range")
		}
	}
	return n, nil
}
