/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2008 jOpenDocument, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU
 * General Public License Version 3 only ("GPL").  
 * You may not use this file except in compliance with the License. 
 * You can obtain a copy of the License at http://www.gnu.org/licenses/gpl-3.0.html
 * See the License for the specific language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 * 
 */

/*
 * Créé le 28 oct. 2004
 * 
 */
package org.jopendocument.dom;

import org.jopendocument.util.JDOMUtils;
import org.jopendocument.util.XPathUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import org.apache.commons.collections.Factory;
import org.jdom.Content;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.xpath.XPath;

/**
 * An OpenDocument XML document, like content.xml ou styles.xml.
 * 
 * @author Sylvain CUAZ
 */
public class ODXMLDocument {

    /**
     * All top-level elements that an office document may contain. Note that only the single xml
     * representation (office:document) contains all of them.
     */
    public static final List<String> TOP_ELEMENTS;
    private static final List<String> ELEMS_ORDER;
    static {
        ELEMS_ORDER = new ArrayList<String>(8);
        ELEMS_ORDER.add("meta");
        ELEMS_ORDER.add("settings");
        ELEMS_ORDER.add("script");
        ELEMS_ORDER.add("font-decls");
        ELEMS_ORDER.add("styles");
        ELEMS_ORDER.add("automatic-styles");
        ELEMS_ORDER.add("master-styles");
        ELEMS_ORDER.add("body");

        TOP_ELEMENTS = ELEMS_ORDER;
    }

    private final Document content;
    private final String version;

    // before making it public, assure that content is really of version "version"
    // eg by checking some namespace
    protected ODXMLDocument(Document content, String version) {
        this.content = content;
        this.version = version;
    }

    public ODXMLDocument(Document content) {
        this(content, NS.getParent(content.getRootElement().getNamespace("office")).getVersion());
    }

    public ODXMLDocument(ODXMLDocument doc) {
        this((Document) doc.content.clone(), doc.version);
    }

    public Document getDocument() {
        return this.content;
    }

    public final String getVersion() {
        return this.version;
    }

    public final NS getNS() {
        return NS.get(this.getVersion());
    }

    // *** children

    public final Element getChild(String childName) {
        return this.getChild(childName, false);
    }

    /**
     * Trouve l'index ou il faut insérer le fils dans ce document.
     * 
     * @param childName le nom du fils que l'on veut insérer.
     * @return l'index ou il faut l'insérer, ou -1 s'il est déjà présent.
     * @throws IllegalArgumentException if childName is not in TOP_ELEMENTS.
     */
    @SuppressWarnings("unchecked")
    private int findInsertIndex(String childName) {
        // eg 6, for "master-styles"
        final int idealIndex = ELEMS_ORDER.indexOf(childName);
        if (idealIndex == -1)
            throw new IllegalArgumentException(childName + " is unknown.");
        if (this.getChild(childName) != null)
            return -1;
        // eg [scripts, font-decls, styles, font-face-decls, automatic-styles, body]
        final List<Element> children = this.getDocument().getRootElement().getChildren();
        final ListIterator<Element> iter = children.listIterator();
        while (iter.hasNext()) {
            final Element elem = iter.next();
            if (ELEMS_ORDER.indexOf(elem.getName()) > idealIndex)
                // eg indexOf("body") == 7 > 6
                // eg return 5
                return iter.previousIndex();
        }
        return children.size();
    }

    /**
     * Insère cet élément à la bonne place. The child should not be already present.
     * 
     * @param child l'élément à insérer, doit être dans TOP_ELEMENTS.
     */
    @SuppressWarnings("unchecked")
    private void insertChild(Element child) {
        // on ajoute au bon endroit
        this.content.getRootElement().getChildren().add(this.findInsertIndex(child.getName()), child);
    }

    /**
     * Return the asked child, optionally creating it.
     * 
     * @param childName the name of the child.
     * @param create whether it should be created in case it doesn't exist.
     * @return the asked child or <code>null</code> if it doesn't exist and create is
     *         <code>false</code>
     */
    public Element getChild(String childName, boolean create) {
        Element child = this.content.getRootElement().getChild(childName, this.getNS().getOFFICE());
        if (create && child == null) {
            child = new Element(childName, this.getNS().getOFFICE());
            this.insertChild(child);
        }
        return child;
    }

    public void setChild(Element elem) {
        if (!elem.getNamespace().equals(this.getNS().getOFFICE()))
            throw new IllegalArgumentException("all children of a document belong to the office namespace.");
        this.content.getRootElement().removeChildren(elem.getName(), elem.getNamespace());
        this.insertChild(elem);
    }

    // *** descendants

    protected final Element getDescendant(String path) throws JDOMException {
        return this.getDescendant(path, false);
    }

    protected final Element getDescendant(String path, boolean create) throws JDOMException {
        Element res = (Element) this.getXPath(path).selectSingleNode(this.getDocument().getRootElement());
        if (res == null && create) {
            final Element parent = this.getDescendant(XPathUtils.parentOf(path), create);
            final Namespace ns = this.getNS().getNS(XPathUtils.namespace(path));
            res = new Element(XPathUtils.localName(path), ns);
            parent.addContent(res);
        }
        return res;
    }

    public final XPath getXPath(String string) throws JDOMException {
        return OOUtils.getXPath(string, this.getVersion());
    }

    public String asString() {
        return JDOMUtils.output(this.content);
    }

    protected static interface ElementTransformer {
        Element transform(Element elem) throws JDOMException;
    }

    protected static final ElementTransformer NOP_ElementTransformer = new ElementTransformer() {
        public Element transform(Element elem) {
            return elem;
        }
    };

    protected void mergeAll(ODXMLDocument other, String path) throws JDOMException {
        this.mergeAll(other, path, null);
    }

    /**
     * Fusionne l'élément spécifié par topElem. Applique addTransf avant l'ajout. Attention seuls
     * les élément (et non les commentaires, text, etc.) de <code>other</code> sont ajoutés.
     * 
     * @param other le document à fusionner.
     * @param path le chemon de l'élément à fusionner, eg "./office:body".
     * @param addTransf la transformation à appliquer avant d'ajouter ou <code>null</code>.
     * @throws JDOMException
     */
    protected void mergeAll(ODXMLDocument other, String path, ElementTransformer addTransf) throws JDOMException {
        this.add(path, -1, other, path, addTransf);
    }

    /**
     * Add the part pointed by <code>rpath</code> of other in this document like child number
     * <code>lindex</code> of the part pointed by <code>lpath</code>.
     * 
     * @param lpath local xpath.
     * @param lindex local index beneath lpath, < 0 meaning the end.
     * @param other the document to add.
     * @param rpath the remote xpath, note: the content of that element will be added NOT the
     *        element itself.
     * @param addTransf the children of rpath will be transformed, can be <code>null</code>.
     * @throws JDOMException if an error occur.
     */
    protected void add(final String lpath, int lindex, ODXMLDocument other, String rpath, ElementTransformer addTransf) throws JDOMException {
        this.add(new Factory() {
            public Object create() {
                try {
                    return getDescendant(lpath, true);
                } catch (JDOMException e) {
                    throw new IllegalStateException("error", e);
                }
            }
        }, lindex, other, rpath, addTransf);
    }

    /**
     * Add the part pointed by <code>rpath</code> of other in this document like child number
     * <code>lindex</code> of <code>elem</code>.
     * 
     * @param elem local element, if <code>null</code> add to rpath see
     *        {@link #mergeAll(ODXMLDocument, String, org.jopendocument.dom.ODXMLDocument.ElementTransformer)}.
     * @param lindex local index beneath lpath, < 0 meaning the end, ignored if elem is
     *        <code>null</code>.
     * @param other the document to add.
     * @param rpath the remote xpath, note: the content of that element will be added NOT the
     *        element itself.
     * @param addTransf the children of rpath will be transformed, can be <code>null</code>.
     * @throws JDOMException if an error occur.
     */
    protected void add(final Element elem, int lindex, ODXMLDocument other, String rpath, ElementTransformer addTransf) throws JDOMException {
        if (elem == null) {
            this.mergeAll(other, rpath, addTransf);
        } else {
            if (!this.getDocument().getRootElement().isAncestor(elem))
                throw new IllegalArgumentException(elem + " not part of " + this);
            this.add(new Factory() {
                public Object create() {
                    return elem;
                }
            }, lindex, other, rpath, addTransf);
        }
    }

    @SuppressWarnings("unchecked")
    private void add(Factory elemF, int lindex, ODXMLDocument other, String rpath, ElementTransformer addTransf) throws JDOMException {
        final Element toAdd = other.getDescendant(rpath);
        // si on a qqchose à ajouter
        if (toAdd != null) {
            final List<Content> cloned = toAdd.cloneContent();
            final List<Content> listToAdd;
            if (addTransf == null) {
                listToAdd = cloned;
            } else {
                listToAdd = new ArrayList<Content>(cloned.size());
                final Iterator iter = cloned.iterator();
                while (iter.hasNext()) {
                    final Content c = (Content) iter.next();
                    if (c instanceof Element) {
                        final Element transformedElem = addTransf.transform((Element) c);
                        if (transformedElem != null)
                            listToAdd.add(transformedElem);
                    }
                }
            }
            // on crée si besoin le "récepteur"
            final Element thisElem = (Element) elemF.create();
            if (lindex < 0)
                thisElem.addContent(listToAdd);
            else
                thisElem.addContent(lindex, listToAdd);
        }
    }

    protected final void addIfNotPresent(ODXMLDocument doc, String path) throws JDOMException {
        this.addIfNotPresent(doc, path, -1);
    }

    /**
     * Adds an element from doc to this, if it's not already there.
     * 
     * @param doc the other document.
     * @param path an XPath denoting an element, and relative to the root element, eg
     *        ./office:settings.
     * @param index the index where to add the element, -1 means the end.
     * @throws JDOMException if a problem occurs with path.
     */
    protected final void addIfNotPresent(ODXMLDocument doc, String path, int index) throws JDOMException {
        final Element myElem = this.getDescendant(path);
        if (myElem == null) {
            final Element otherElem = doc.getDescendant(path);
            if (otherElem != null) {
                final Element myParent = this.getDescendant(XPathUtils.parentOf(path));
                if (index == -1)
                    myParent.addContent((Element) otherElem.clone());
                else
                    myParent.addContent(index, (Element) otherElem.clone());
            }
        }
    }

}