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

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.validation.Errors;

import ru.yandex.canvas.model.elements.Domain;

public class UrlValidator extends ElementValidator<Domain> {
    public static final String PROTOCOL_MESSAGE = "{javax.validation.constraints.Protocol.message}";
    private static final String FORMAT_MESSAGE = "{javax.validation.constraints.Pattern.message}";
    private static final List<String> VALID_URL_PROTOCOLS = List.of("http", "https");

    private boolean protocolRequired;

    @Override
    public boolean isSupported(Domain target) {
        if (target == null || !target.getAvailable()) {
            return false;
        }
        return true;
    }

    @Override
    public void validate(Domain target, @NonNull Errors errors) {
        String link = target.getOptions().getContent();
        try {
            URI uri = new URI(link);
            if (protocolRequired && (uri.getScheme() == null || !VALID_URL_PROTOCOLS.contains(uri.getScheme()))) {
                String[] errorArgs = new String[]{"protocols", String.join("/", VALID_URL_PROTOCOLS)};
                errors.rejectValue("options.content", "format.error", errorArgs, PROTOCOL_MESSAGE);
            }
        } catch (URISyntaxException ex) {
            errors.rejectValue("options.content", "format.error", FORMAT_MESSAGE);
        }
    }

    public boolean isProtocolRequired() {
        return protocolRequired;
    }

    public void setProtocolRequired(boolean protocolRequired) {
        this.protocolRequired = protocolRequired;
    }
}
