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;

@Stateless
public class ElementUpdateValidator extends Validator<ElementRequestDTO> {

    public static final String PRICE_POSITIVE = "Price must be positive or null";
    public static final String NO_IMAGE_UPDATE = "Can not update image";
    public static final String URL_INVALID = "URL provided is invalid";
    public static final String ONE_UPDATED_FIELD_REQUIRED = "At least one field must be updated";

    @Override
    protected void validate(ElementRequestDTO data) {
        int nb = 0;
        if (StringUtils.isNotBlank(data.getName())) {
            nb++;
        }
        if (StringUtils.isNotBlank(data.getDescription())) {
            nb++;
        }
        if (StringUtils.isNotBlank(data.getLink())) {
            String[] scheme = {"http", "https"};
            UrlValidator urlValidator = new UrlValidator(scheme);
            assertTrue(urlValidator.isValid(data.getLink()), URL_INVALID);
            nb++;
        }
        if (StringUtils.isNotBlank(data.getAddress())) {
            nb++;
        }
        if (data.getPrice() != null) {
            assertTrue(data.getPrice() >= 0, PRICE_POSITIVE);
            nb++;
        }
        assertTrue(data.getImage() == null || (data.getImage() != null && data.getImage().isEmpty()), NO_IMAGE_UPDATE);
        assertTrue(nb > 0, ONE_UPDATED_FIELD_REQUIRED);
    }

}
