package validator

import (
	"errors"
	"fmt"
	"regexp"
)

const (
	visibleASCIIRegex string = "^[\x20-\x7E]+$"
)

var (
	visibleASCIIValidator = regexp.MustCompile(visibleASCIIRegex)
	errInternal           = errors.New("could not validate input")
)

func IsValidVisibleASCII(str string) bool {
	return visibleASCIIValidator.MatchString(str)
}

func IsMultilineVisible(str string) bool {
	return regexp.MustCompile("[[:graph:]]|[[:space:]]").MatchString(str)
}

func Validate(field string, validator func(string) bool) error {
	isValid := validator(field)
	if !isValid {
		return fmt.Errorf("%q is an invalid input", field)
	}

	return nil
}

func ValidateWithError(field string, validator func(string) (bool, error)) error {
	isValid, err := validator(field)
	if err != nil {
		return errInternal
	}

	if !isValid {
		return fmt.Errorf("%q is an invalid input", field)
	}

	return nil
}

func IsInternalError(err error) bool {
	return err == errInternal
}
