package ru.yandex.canvas.model.validation.presetbased.creative;

import java.net.URI;
import java.net.URISyntaxException;

import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;

import ru.yandex.canvas.model.CreativeData;
import ru.yandex.canvas.model.MediaSet;
import ru.yandex.canvas.model.MediaSetSubItem;
import ru.yandex.canvas.model.elements.Element;
import ru.yandex.canvas.model.validation.AvatarsServiceContainer;
import ru.yandex.canvas.service.AvatarsService;

public class AllowedDomainsValidator extends MediaSetValidator<Element> implements AvatarsServiceContainer {

    private static final Logger logger = LoggerFactory.getLogger(AllowedDomainsValidator.class);

    private static final String MESSAGE = "{domain_is_not_allowed}";

    private AvatarsService avatarsService;

    @Override
    public void setAvatarsService(AvatarsService avatarsService) {
        this.avatarsService = avatarsService;
    }

    private boolean isUrlAllowed(String value) {
        if (!StringUtils.isEmpty(value)) {
            try {
                final String host = new URI(value).getHost();
                return host != null && host.equalsIgnoreCase(avatarsService.getReadServiceHost());
            } catch (URISyntaxException e) {
                logger.error("Invalid URL", e);
                return false;
            }
        }
        return true;
    }

    @Override
    protected void validate(Element element, MediaSet mediaSet, CreativeData creativeData, @NonNull Errors errors) {
        for (MediaSetSubItem item : getSubItems(mediaSet)) {
            if (!isUrlAllowed(item.getUrl())) {
                errors.rejectValue(null, "domain.is.not.allowed", MESSAGE);
                return;
            }
        }
    }
}
