package ru.yandex.wmtools.common.sita;

import java.net.URI;
import java.net.URL;

import ru.yandex.wmtools.common.util.uri.WebmasterUriUtils;

public class SitaUrlFetchRequestBuilder {
    private URI uri;
    private DocumentFormatEnum documentFormat = DocumentFormatEnum.DF_NO_DOC;
    private RobotsTxtFormatEnum robotsTxtFormat = RobotsTxtFormatEnum.RF_NO_ROBOTS_TXT;
    private UserAgentEnum userAgent = UserAgentEnum.WEBMASTER;
    private boolean checkAllowedInRobotsTxt = true;
    private Integer ifModifiedSince;
    private Integer timeout = 8;
    private Integer freshness = 0;
    private SitaRequestTimeout requestTimeout = SitaRequestTimeout.DEFAULT;

    public SitaUrlFetchRequestBuilder(URI uri) {
        this.uri = uri;
    }

    public SitaUrlFetchRequestBuilder(URL url) {
        try {
//            this.uri = UriComponentsBuilder.fromHttpUrl(url.toString()).build(true).toUri();
            this.uri = WebmasterUriUtils.toOldUri(url.toString());
        } catch (Exception e) {
            throw new SitaException("Unable to convert host URL to URI", e);
        }
    }

    public SitaUrlFetchRequestBuilder setDocumentFormat(DocumentFormatEnum documentFormat) {
        this.documentFormat = documentFormat;
        return this;
    }

    public SitaUrlFetchRequestBuilder setRobotsTxtFormat(RobotsTxtFormatEnum robotsTxtFormat) {
        this.robotsTxtFormat = robotsTxtFormat;
        return this;
    }

    public SitaUrlFetchRequestBuilder setUserAgent(UserAgentEnum userAgent) {
        this.userAgent = userAgent;
        return this;
    }

    public SitaUrlFetchRequestBuilder setCheckAllowedInRobotsTxt(boolean checkAllowedInRobotsTxt) {
        this.checkAllowedInRobotsTxt = checkAllowedInRobotsTxt;
        return this;
    }

    public SitaUrlFetchRequestBuilder setIfModifiedSince(Integer ifModifiedSince) {
        this.ifModifiedSince = ifModifiedSince;
        return this;
    }

    public SitaUrlFetchRequestBuilder setTimeout(Integer timeout) {
        this.timeout = timeout;
        return this;
    }

    public SitaUrlFetchRequestBuilder setFreshness(Integer freshness) {
        this.freshness = freshness;
        return this;
    }

    public SitaUrlFetchRequestBuilder setRequestTimeout(SitaRequestTimeout requestTimeout) {
        this.requestTimeout = requestTimeout;
        if (this.timeout < requestTimeout.getTimeout()) {
            this.timeout = requestTimeout.getTimeout();
        }
        return this;
    }

    public SitaUrlFetchRequest createSitaUrlFetchRequest() {
        return new SitaUrlFetchRequest(uri.normalize(),
                documentFormat,
                robotsTxtFormat,
                userAgent,
                checkAllowedInRobotsTxt,
                ifModifiedSince,
                timeout,
                freshness,
                requestTimeout);
    }
}
