package dev.fyloz.trial.colorrecipesexplorer.model.validation

import javax.validation.Constraint
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
import javax.validation.Payload
import kotlin.reflect.KClass

private const val MESSAGE = "must be null or not blank"

@Target(AnnotationTarget.FIELD)
@MustBeDocumented
@Constraint(validatedBy = [NullOrNotBlankValidator::class])
annotation class NullOrNotBlank(
        val message: String = MESSAGE,
        val groups: Array<KClass<*>> = [],
        val payload: Array<KClass<out Payload>> = []
)

class NullOrNotBlankValidator : ConstraintValidator<NullOrNotBlank, String> {
    var message = MESSAGE

    override fun initialize(constraintAnnotation: NullOrNotBlank) {
        message = constraintAnnotation.message
    }

    override fun isValid(value: String?, context: ConstraintValidatorContext): Boolean {
        return (value == null || value.isNotBlank()).apply {
            if (!this) context.buildConstraintViolationWithTemplate(message)
        }
    }
}
