package ru.yandex.webmaster3.api.searchurls.data;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.Nullable;
import ru.yandex.webmaster3.storage.searchurl.samples.data.UrlStatusInfo;
import ru.yandex.wmtools.common.util.http.YandexHttpStatus;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author leonidrom
 */
@RequiredArgsConstructor
@Getter
public class ApiExcludedSearchUrlInfo {
    private final ApiExcludedUrlStatusEnum excludedUrlStatus;

    @Nullable
    private final Integer badHttpStatus;

    @Nullable
    private final URL targetUrl;

    @Nullable
    public static ApiExcludedSearchUrlInfo fromUrlStatusInfo(UrlStatusInfo coreStatusInfo) {
        ApiExcludedUrlStatusEnum excludedStatus = ApiExcludedUrlStatusEnum.fromCoreStatus(coreStatusInfo.getStatus());
        if (excludedStatus == null) {
            // страница в поиске
            return null;
        }

        Integer badHttpStatus = null;
        if (excludedStatus == ApiExcludedUrlStatusEnum.HTTP_ERROR) {
            badHttpStatus = YandexHttpStatus.toStandardHttpCode(
                    YandexHttpStatus.parseCode(coreStatusInfo.getHttpCode()));
        }

        URL targetUrl = null;
        if (coreStatusInfo.getTargetUrl() != null) {
            try {
                targetUrl = new URL(coreStatusInfo.getTargetUrl());
            } catch (MalformedURLException e) {
                // такого быть не должно
            }
        }

        return new ApiExcludedSearchUrlInfo(excludedStatus, badHttpStatus, targetUrl);
    }
}
