package ru.yandex.webmaster3.viewer.http.crawl;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.host.service.HostOwnerService;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.url.checker3.service.UrlCheckDataBlocksService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.util.uri.WebmasterUriUtils;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.UUID;

/**
 * @author leonidrom
 */
@Description("Запросить проверку роторения урла")
@WriteAction
@Category("crawl")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Component("/host/rotorCheck/start")
public class StartUrlRotorCheckAction extends AbstractUserVerifiedHostAction<StartUrlRotorCheckRequest, StartUrlRotorCheckResponse> {
    private final HostOwnerService hostOwnerService;
    private final UrlCheckDataBlocksService urlCheckDataBlocksService;

    @Override
    public StartUrlRotorCheckResponse process(StartUrlRotorCheckRequest request) {
        var urlCheckParams = request.getRequestParams();

        URI uri;
        try {
            uri = processUrl(request.getHostId(), urlCheckParams.getUrl());
        } catch (Exception e) {
            return new StartUrlRotorCheckResponse.InvalidUrlResponse();
        }

        WebmasterHostId hostOfUrl = IdUtils.urlToHostId(uri);
        if (!compareHosts(request.getHostId(), hostOfUrl) && !hostOwnerService.isSameOwner(request.getHostId(), hostOfUrl)) {
            return new StartUrlRotorCheckResponse.UrlIsNotFromHostResponse();
        }

        URL url;
        try {
            url = uri.toURL();
        } catch (MalformedURLException e) {
            return new StartUrlRotorCheckResponse.InvalidUrlResponse();
        }

        urlCheckParams.url = url.toExternalForm();
        UUID requestId = urlCheckDataBlocksService.sendRotorCheckRequest(urlCheckParams);

        return new StartUrlRotorCheckResponse.NormalResponse(requestId);
    }

    private URI processUrl(WebmasterHostId hostId, String urlS) throws UserException {
        URI uri;
        if (urlS.startsWith("/")) {
            uri = WebmasterUriUtils.toOldUri(IdUtils.hostIdToUrl(hostId) + urlS);
        } else {
            uri = WebmasterUriUtils.toOldUri(urlS);
        }

        if (StringUtils.isEmpty(uri.getPath())) {
            uri = uri.resolve("/");
        }

        return uri;
    }

    private boolean compareHosts(WebmasterHostId expected, WebmasterHostId actual) {
        if (expected.equals(actual)) {
            return true;
        }
        String expectedHostPart = expected.getPunycodeHostname();
        String actualHostPart = actual.getPunycodeHostname();
        return WwwUtil.equalsIgnoreWww(actualHostPart, expectedHostPart);
    }
}
