package org.xbib.io.webdav.client;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xbib.io.webdav.api.DavConstants;
import org.xbib.io.webdav.api.XMLizable;
import org.xbib.io.webdav.common.DavException;
import org.xbib.io.webdav.common.DomUtil;
import org.xbib.io.webdav.common.ElementIterator;

public class UnbindInfo implements XMLizable {

    private String segment;

    private UnbindInfo() {
    }

    public UnbindInfo(String segment) {
        this.segment = segment;
    }

    public String getSegment() {
        return this.segment;
    }

    /**
     * Build an <code>UnbindInfo</code> object from the root element present
     * in the request body.
     *
     * @param root the root element of the request body
     * @return a UnbindInfo object containing a segment identifier
     * @throws DavException if the UNBIND request is malformed
     */
    public static UnbindInfo createFromXml(Element root) throws DavException {
        if (!DomUtil.matches(root, "unbind", DavConstants.NAMESPACE)) {
            //LOG.log(Level.WARNING, "DAV:unbind element expected");
            throw new DavException(400);
        }
        String segment = null;
        ElementIterator it = DomUtil.getChildren(root);
        while (it.hasNext()) {
            Element elt = it.nextElement();
            if (DomUtil.matches(elt, "segment", DavConstants.NAMESPACE)) {
                if (segment == null) {
                    segment = DomUtil.getText(elt);
                } else {
                    //LOG.log(Level.WARNING, "unexpected multiple occurrence of DAV:segment element");
                    throw new DavException(400);
                }
            } else {
                //LOG.log(Level.WARNING, "unexpected element " + elt.getLocalName());
                throw new DavException(400);
            }
        }
        if (segment == null) {
            //LOG.log(Level.WARNING, "DAV:segment element expected");
            throw new DavException(400);
        }
        return new UnbindInfo(segment);
    }

    /**
     * @see XMLizable#toXml(Document)
     */
    public Element toXml(Document document) {
        Element unbindElt = DomUtil.createElement(document, "unbind", DavConstants.NAMESPACE);
        Element segElt = DomUtil.createElement(document, "segment", DavConstants.NAMESPACE, this.segment);
        unbindElt.appendChild(segElt);
        return unbindElt;
    }
}
