package org.xbib.io.webdav.common;

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 java.util.ArrayList;
import java.util.List;

/**
 * <code>OrderPatch</code> represents the mandatory request body of an
 * ORDERPATCH request. RFC 3648 defines the following structure for it:<br>
 * <pre>
 * &lt;!ELEMENT orderpatch (ordering-type?, order-member*) &gt;
 * &lt;!ELEMENT order-member (segment, position) &gt;
 * &lt;!ELEMENT position (first | last | before | after) &gt;
 * &lt;!ELEMENT segment (#PCDATA) &gt;
 * &lt;!ELEMENT first EMPTY &gt;
 * &lt;!ELEMENT last EMPTY &gt;
 * &lt;!ELEMENT before segment &gt;
 * &lt;!ELEMENT after segment &gt;
 * </pre>
 */
public class OrderPatch implements XMLizable {

    private final Member[] instructions;

    private final String orderingType;

    /**
     * Create a new <code>OrderPath</code> object.
     *
     * @param orderingType
     * @param instruction
     */
    public OrderPatch(String orderingType, Member instruction) {
        this(orderingType, new Member[]{instruction});
    }

    /**
     * Create a new <code>OrderPath</code> object.
     *
     * @param orderingType
     * @param instructions
     */
    public OrderPatch(String orderingType, Member[] instructions) {
        if (orderingType == null || instructions == null) {
            throw new IllegalArgumentException("ordering type and instructions cannot be null.");
        }
        this.orderingType = orderingType;
        this.instructions = instructions;
    }

    /**
     * Return the ordering type.
     *
     * @return ordering type
     */
    public String getOrderingType() {
        return orderingType;
    }

    /**
     * Return an array of {@link Member} objects defining the re-ordering
     * instructions to be applied to the requested resource.
     *
     * @return ordering instructions.
     */
    public Member[] getOrderInstructions() {
        return instructions;
    }

    /**
     * @param document
     * @return
     */
    public Element toXml(Document document) {
        Element orderPatch = DomUtil.createElement(document, "orderpatch", DavConstants.NAMESPACE);
        // add DAV:ordering-type below DAV:orderpatch
        Element otype = DomUtil.addChildElement(orderPatch, "ordering-type", DavConstants.NAMESPACE);
        otype.appendChild(DomUtil.hrefToXml(orderingType, document));
        // add DAV:member elements below DAV:orderpatch
        for (Member instruction : instructions) {
            orderPatch.appendChild(instruction.toXml(document));
        }
        return orderPatch;
    }

    /**
     * Create a new <code>OrderPath</code> object.
     *
     * @param orderPatchElement
     * @throws IllegalArgumentException if the specified Xml element was not valid.
     */
    public static OrderPatch createFromXml(Element orderPatchElement) throws DavException {
        if (!DomUtil.matches(orderPatchElement, "orderpatch", DavConstants.NAMESPACE)) {
            //LOG.log(Level.WARNING, "ORDERPATH request body must start with an 'orderpatch' element.");
            throw new DavException(400);
        }

        // retrieve the href of the orderingtype element
        String orderingType;
        Element otype = DomUtil.getChildElement(orderPatchElement, "ordering-type", DavConstants.NAMESPACE);
        if (otype != null) {
            orderingType = DomUtil.getChildText(otype, DavConstants.XML_HREF, DavConstants.NAMESPACE);
        } else {
            //LOG.log(Level.WARNING, "ORDERPATH request body must contain an 'ordering-type' child element.");
            throw new DavException(400);
        }

        // set build the list of ordering instructions
        List<Member> tmpList = new ArrayList<Member>();
        ElementIterator it = DomUtil.getChildren(orderPatchElement, "order-member", DavConstants.NAMESPACE);
        while (it.hasNext()) {
            Element el = it.nextElement();
            try {
                // retrieve text 'DAV:segment' child of this DAV:order-member element
                String segment = DomUtil.getChildText(el, "segment", DavConstants.NAMESPACE);
                // retrieve the 'DAV:position' child element
                Position pos = Position.createFromXml(DomUtil.getChildElement(el, "position", DavConstants.NAMESPACE));
                Member om = new Member(segment, pos);
                tmpList.add(om);
            } catch (IllegalArgumentException e) {
                //LOG.log(Level.WARNING, "Invalid element in 'orderpatch' request body: " + e.getMessage());
                throw new DavException(400);
            }
        }
        Member[] instructions = tmpList.toArray(new Member[tmpList.size()]);
        return new OrderPatch(orderingType, instructions);
    }

    /**
     * Internal class <code>Member</code> represents the 'Order-Member' children
     * elements of an 'OrderPatch' request body present in the ORDERPATCH request.
     */
    public static class Member implements XMLizable {

        private final String memberHandle;
        private final Position position;

        /**
         * Create a new <code>Member</code> object.
         *
         * @param memberHandle
         * @param position
         */
        public Member(String memberHandle, Position position) {
            this.memberHandle = memberHandle;
            this.position = position;
        }

        /**
         * Return the handle of the internal member to be reordered.
         *
         * @return handle of the internal member.
         */
        public String getMemberHandle() {
            return memberHandle;
        }

        /**
         * Return the position where the internal member identified by the
         * member handle should be placed.
         *
         * @return position for the member after the request.
         * @see #getMemberHandle()
         */
        public Position getPosition() {
            return position;
        }

        @Override
        public Element toXml(Document document) {
            Element memberElem = DomUtil.createElement(document, "order-member", DavConstants.NAMESPACE);
            DomUtil.addChildElement(memberElem,  "segment", DavConstants.NAMESPACE, memberHandle);
            memberElem.appendChild(position.toXml(document));
            return memberElem;
        }

    }
}
