package com.wishurgift.entry.validator;

import com.wishurgift.service.dto.request.ElementRequestDTO;
import com.wishurgift.utils.StringUtils;
import org.apache.commons.validator.routines.UrlValidator;

import javax.ejb.Stateless;
import javax.inject.Inject;

@Stateless
public class ElementAddValidator extends Validator<ElementRequestDTO> {

    public static final String NAME_REQUIRED = "Name is required";
    public static final String PRICE_POSITIVE = "Price must be positive or null";
    public static final String URL_INVALID = "URL provided is invalid";

    @Inject
    private ImageValidator imageValidator;

    @Override
    protected void validate(ElementRequestDTO data) {
        assertTrue(StringUtils.isNotBlank(data.getName()), NAME_REQUIRED);
        if (data.getPrice() != null) {
            assertTrue(data.getPrice() >= 0, PRICE_POSITIVE);
        }
        if (data.getImage() != null && !data.getImage().isEmpty()) {
            assertTrue(imageValidator.isValid(data.getImage()), imageValidator.getAllErrors());
        }
        if (StringUtils.isNotBlank(data.getLink())) {
            String[] scheme = {"http", "https"};
            UrlValidator urlValidator = new UrlValidator(scheme);
            assertTrue(urlValidator.isValid(data.getLink()), URL_INVALID);
        }
    }

}
