package org.xbib.io.webdav.client.methods;

import org.xbib.io.webdav.api.DavConstants;
import org.xbib.io.webdav.client.ReportInfo;
import org.xbib.io.webdav.common.DepthHeader;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
 * Represents an HTTP REPORT request.
 *
 * @see <a href="http://webdav.org/specs/rfc3253.html#rfc.section.3.6">RFC 3253, Section 3.6</a>
 */
public class Report extends AbstractMethod {

    private final ReportInfo reportInfo;

    private final boolean isDeep;

    public Report(ReportInfo reportInfo) {
        this.reportInfo = reportInfo;
        this.isDeep = reportInfo.getDepth() > DavConstants.DEPTH_0;
    }

    @Override
    public String method() {
        return "REPORT";
    }

    @Override
    public HttpRequest.BodyPublisher bodyPublisher() {
        return publish(reportInfo);
    }

    @Override
    public void accept(HttpRequest.Builder httpRequest) {
        super.accept(httpRequest);
        DepthHeader dh = new DepthHeader(reportInfo.getDepth());
        httpRequest.setHeader(dh.getHeaderName(), dh.getHeaderValue());
    }

    @Override
    public boolean succeeded(HttpResponse<?> response) {
        int statusCode = response.statusCode();
        if (isDeep) {
            return statusCode == 207;
        } else {
            return statusCode == 200 || statusCode == 207;
        }
    }
}
