package ru.yandex.webmaster3.core.sitemap;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Value;
import lombok.With;
import org.joda.time.DateTime;

import ru.yandex.webmaster3.core.data.HttpCodeInfo;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.sitemap.raw.HostRelatedSitemaps;


/**
 * Created by Oleg Bazdyrev on 19/10/2021.
 */
@Value
@Builder
@Getter
@With
@AllArgsConstructor(onConstructor_ = @JsonCreator)
public class SitemapInfo {
    @JsonProperty("hostId")
    WebmasterHostId hostId;
    @JsonProperty("id")
    UUID id;
    @JsonProperty("parentId")
    UUID parentId;
    @JsonProperty("url")
    String url;
    @JsonProperty("referrer")
    String referrer;
    @JsonProperty("httpCodeInfo")
    HttpCodeInfo httpCodeInfo;
    @JsonProperty("lastAccess")
    DateTime lastAccess;
    @JsonProperty("lastChange")
    DateTime lastChange;
    @JsonProperty("lastUrlsChange")
    DateTime lastUrlsChange;
    @JsonProperty("urlCount")
    long urlCount;
    @JsonProperty("errorCount")
    long errorCount;
    @JsonProperty("sources")
    Set<HostRelatedSitemaps.SitemapSource> sources;
    @JsonProperty("redirTarget")
    String redirTarget;
    @JsonProperty("parsed")
    boolean parsed;
    @JsonProperty("index")
    boolean index;
    @JsonProperty("urls")
    List<String> urls;
    @JsonProperty("errors")
    List<SitemapErrorInfo> errors;
    @JsonProperty("childrenCount")
    long childrenCount;

    public HostSitemap toHostSitemap() {
        return new HostSitemap(id, url, sources, parentId, lastAccess, httpCodeInfo, redirTarget,
                index, urlCount, (int) errorCount, (int) childrenCount);
    }

    public HostSitemapInfo toHostSitemapInfo() {
        List<HostSitemapInfo.SitemapError> errors = new ArrayList<>();
        List<HostSitemapInfo.SitemapError> warnings = new ArrayList<>();
        for (SitemapErrorInfo rawError : this.errors) {
            if (rawError.getCode() == null) {
                continue;
            }
            if (rawError.getCode().isError()) {
                errors.add(rawError.toSitemapError());
            } else {
                warnings.add(rawError.toSitemapError());
            }
        }
        return new HostSitemapInfo(url, lastAccess, httpCodeInfo, redirTarget, urlCount,
                index ? SitemapType.SITEMAPINDX : SitemapType.SITEMAP, errors, warnings);
    }

}
