package validator

import (
	"regexp"
	"strings"

	"github.com/go-playground/validator/v10"
	"github.com/pkg/errors"
	"github.com/fiskerinc/cloud-services/pkg/vindecoder"
)

func validateVIN(fl validator.FieldLevel) bool {
	ok := ValidateVINSimple(fl.Field().String())

	return ok
}

func validateVINs(fl validator.FieldLevel) bool {
	vins := strings.Split(fl.Field().String(), ",")

	for _, vin := range vins {
		ok := vindecoder.ValidateVINSimple(vin)
		if !ok {
			return false
		}

		ok = vindecoder.VerifyVinCheckDigit(vin)
		if !ok {
			return false
		}
	}

	return true
}

func validateVINSuffix(fl validator.FieldLevel) bool {
	ok, err := ValidateVINSuffixSimple(fl.Field().String())

	return ok && err == nil
}

func ValidateVINSuffixSimple(vin string) (bool, error) {
	matched, err := regexp.Match(`^[a-hj-npr-zA-HJ-NPR-Z0-9]{7}$`, []byte(vin))
	if err != nil {
		return matched, errors.WithStack(err)
	}
	return matched, nil
}

func validateICCID(fl validator.FieldLevel) bool {
	ok, err := ValidateICCIDSimple(fl.Field().String())

	return ok && err == nil
}

func ValidateICCIDSimple(iccid string) (bool, error) {
	matched, err := regexp.Match(`^[0-9]{5,50}F{0,1}$`, []byte(iccid))
	if err != nil {
		return matched, errors.Wrapf(err, "")
	}

	return matched, nil
}

func validateVinCheckDigit(fl validator.FieldLevel) bool {
	var vin = fl.Field().String()
	return vindecoder.VerifyVinCheckDigit(vin)
}

func ValidateVINSimple(vin string) (valid bool) {
	return vindecoder.ValidateVINSimple(vin)
}