package ru.yandex.webmaster3.api.http.rest.jackson.deser;

import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.FromStringDeserializer;
import org.apache.commons.lang3.StringUtils;
import ru.yandex.wmtools.common.error.AbstractWMToolsException;
import ru.yandex.wmtools.common.util.uri.WebmasterUriUtils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author avhaliullin
 */
public class ApiURLDeserializer extends FromStringDeserializer<URL> {

    public ApiURLDeserializer() {
        super(URL.class);
    }

    @Override
    protected URL _deserialize(String value, DeserializationContext ctxt) throws IOException {
        URL url;
        try {
            url = WebmasterUriUtils.toOldUri(value).toURL();
        } catch (AbstractWMToolsException | MalformedURLException | RuntimeException e) {
            throw ctxt.mappingException("Invalid url: \"%s\"", value);
        }

        String host = url.getHost();
        if (StringUtils.isEmpty(host)) {
            host = url.getAuthority();
        }
        if (StringUtils.isEmpty(host)) {
            throw ctxt.mappingException("Invalid url: no host \"%s\"", value);
        }
        if (host.indexOf('.') < 0) {
            throw ctxt.mappingException("Invalid url: invalid host \"%s\"", value);
        }

        return url;
    }
}
