package de.champonthis.buntspecht.controller.validation;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import de.champonthis.buntspecht.model.Turnover;

@Component
public class TurnoverValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(Turnover.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Turnover turnover = (Turnover) target;

        if (!StringUtils.hasText(turnover.getCustomer())) {
            errors.rejectValue("customer", "REQUIRED");
        }

        if (!StringUtils.hasText(turnover.getMotif())) {
            errors.rejectValue("motif", "REQUIRED");
        }

        if (turnover.getPrice() == 0) {
            errors.rejectValue("price", "REQUIRED");
        }

        if (turnover.getPrice() < 0) {
            errors.rejectValue("price", "POSITIVE_VALUE");
        }
    }
}
