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

import org.jetbrains.annotations.Nullable;
import org.joda.time.DateTime;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.data.HttpCodeInfo;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.core.util.TimeUtils;
import ru.yandex.webmaster3.storage.indexing2.samples.data.IndexedUrlSample;
import ru.yandex.wmtools.common.util.http.YandexHttpStatus;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Optional;

/**
 * @author avhaliullin
 */
public class ApiIndexedPageSample {
    private final IndexingStatusEnum status;
    private final Optional<Integer> httpCode;
    private final URL url;
    private final DateTime accessDate;

    public ApiIndexedPageSample(IndexingStatusEnum status, Optional<Integer> httpCode, URL url, DateTime accessDate) {
        this.status = status;
        this.httpCode = httpCode;
        this.url = url;
        this.accessDate = accessDate;
    }

    @Description("обобщенный статус загрузки")
    public IndexingStatusEnum getStatus() {
        return status;
    }

    @Description("http-код, если есть")
    public Optional<Integer> getHttpCode() {
        return httpCode;
    }

    @Description("адрес страницы")
    public URL getUrl() {
        return url;
    }

    @Description("дата загрузки страницы")
    public DateTime getAccessDate() {
        return accessDate;
    }

    @Nullable
    public static ApiIndexedPageSample fromIndexedUrlSample(WebmasterHostId hostId, IndexedUrlSample sample) {
        URL fullUrl;
        try {
            String relativeUrl = sample.getUrl();
            fullUrl = new URL(IdUtils.hostIdToReadableUrl(hostId) + relativeUrl);
        } catch (MalformedURLException e) {
            // should not happen
            return null;
        }

        HttpCodeInfo codeInfo = sample.getCurrentCode();
        IndexingStatusEnum status = IndexingStatusEnum.of(codeInfo.getCode());
        Optional<Integer> httpCode = Optional.ofNullable(YandexHttpStatus.toStandardHttpCode(codeInfo.getStatus()));
        DateTime lastAccess = sample.getLastAccess().toDateTime(TimeUtils.EUROPE_MOSCOW_ZONE);

        return new ApiIndexedPageSample(status, httpCode, fullUrl, lastAccess);
    }
}
