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

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

/**
 * Represents an HTTP PROPFIND request.
 *
 * @see <a href="http://webdav.org/specs/rfc4918.html#rfc.section.9.1">RFC 4918, Section 9.1</a>
 */
public class Propfind extends AbstractMethod {

    private final int propfindType;

    private final DavPropertyNameSet names;

    private final int depth;

    public Propfind(DavPropertyNameSet names, int depth) {
        this(DavConstants.PROPFIND_BY_PROPERTY, names, depth);
    }

    public Propfind(int propfindType, int depth) {
        this(propfindType, new DavPropertyNameSet(), depth);
    }

    public Propfind(int propfindType, DavPropertyNameSet names, int depth) {
        this.propfindType = propfindType;
        this.names = names;
        this.depth = depth;
    }

    @Override
    public HttpRequest.BodyPublisher bodyPublisher() {
        return publish(new PropfindInfo(propfindType, names));
    }

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

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

    @Override
    public boolean succeeded(HttpResponse<?> response) {
        return response.statusCode() == 207;
    }
}
