/**
 * Distribution License:
 * JSword is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License, version 2.1 or later
 * as published by the Free Software Foundation. This program is distributed
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * The License is available on the internet at:
 *       http://www.gnu.org/copyleft/lgpl.html
 * or by writing to:
 *      Free Software Foundation, Inc.
 *      59 Temple Place - Suite 330
 *      Boston, MA 02111-1307, USA
 *
 * Copyright: 2005
 *     The copyright to this program is held by its authors.
 *
 */
package org.crosswire.jsword.passage;

import java.util.Iterator;

/**
 * An implementation of some of the easier methods from Key.
 * 
 * @see gnu.lgpl.License The GNU Lesser General Public License for details.
 * @author Joe Walker
 */
public abstract class AbstractKeyList implements Key {
    /**
     * Build an AbstractKeyList with the given name.
     * 
     * @param name
     */
    protected AbstractKeyList(String name) {
        this.name = name;
    }

    /* (non-Javadoc)
     * @see org.crosswire.jsword.passage.Key#isEmpty()
     */
    public boolean isEmpty() {
        return getCardinality() == 0;
    }

    /* (non-Javadoc)
     * @see org.crosswire.jsword.passage.Key#contains(org.crosswire.jsword.passage.Key)
     */
    public boolean contains(Key key) {
        return indexOf(key) >= 0;
    }

    /* (non-Javadoc)
     * @see org.crosswire.jsword.passage.Key#retainAll(org.crosswire.jsword.passage.Key)
     */
    public void retainAll(Key key) {
        Key shared = new DefaultKeyList();
        shared.addAll(key);
        retain(this, shared);
    }

    /**
     * Utility to remove all the keys from alter that are not in base
     * 
     * @param alter
     *            The key to remove keys from
     * @param base
     *            The check key
     */
    protected static void retain(Key alter, Key base) {
        Iterator<Key> it = alter.iterator();
        while (it.hasNext()) {
            Key sublist = it.next();
            if (sublist.canHaveChildren()) {
                retain(sublist, base);
                if (sublist.isEmpty()) {
                    it.remove();
                }
            } else {
                if (!base.contains(sublist)) {
                    it.remove();
                }
            }
        }
    }

    @Override
    public String toString() {
        return getName();
    }

    /**
     * Override the default name with a custom name. If the name is null then a
     * name will be generated by concatenating the names of all the elements of
     * this node.
     * @param name 
     */
    public void setName(String name) {
        this.name = name;
    }

    /* (non-Javadoc)
     * @see org.crosswire.jsword.passage.Key#getName()
     */
    public String getName() {
        if (name != null) {
            return name;
        }

        DefaultKeyVisitor visitor = new NameVisitor();
        KeyUtil.visit(this, visitor);
        return visitor.toString();
    }

    /* (non-Javadoc)
     * @see org.crosswire.jsword.passage.Key#getName(org.crosswire.jsword.passage.Key)
     */
    public String getName(Key base) {
        return getName();
    }

    /* (non-Javadoc)
     * @see org.crosswire.jsword.passage.Key#getRootName()
     */
    public String getRootName() {
        return getName();
    }

    /* (non-Javadoc)
     * @see org.crosswire.jsword.passage.Key#getOsisRef()
     */
    public String getOsisRef() {
        DefaultKeyVisitor visitor = new OsisRefVisitor();
        KeyUtil.visit(this, visitor);
        return visitor.toString();
    }

    /* (non-Javadoc)
     * @see org.crosswire.jsword.passage.Key#getOsisID()
     */
    public String getOsisID() {
        DefaultKeyVisitor visitor = new OsisIDVisitor();
        KeyUtil.visit(this, visitor);
        return visitor.toString();
    }

    @Override
    public boolean equals(Object obj) {
        // Since this can not be null
        if (obj == null) {
            return false;
        }

        // Check that that is the same as this
        // Don't use instanceOf since that breaks inheritance
        if (!obj.getClass().equals(this.getClass())) {
            return false;
        }

        return compareTo((Key) obj) == 0;
    }

    @Override
    public int hashCode() {
        return getName().hashCode();
    }

    /* (non-Javadoc)
     * @see java.lang.Comparable#compareTo(java.lang.Object)
     */
    public int compareTo(Key that) {

        if (this == that) {
            return 0;
        }

        if (that == null) {
            // he is empty, we are not so he is greater
            return -1;
        }

        int ret = this.getName().compareTo(that.getName());

        if (ret != 0) {
            return ret;
        }

        // Compare the contents.
        Iterator<Key> thisIter = this.iterator();
        Iterator<Key> thatIter = that.iterator();

        Key thisfirst = null;
        Key thatfirst = null;

        if (thisIter.hasNext()) {
            thisfirst = thisIter.next();
        }

        if (thatIter.hasNext()) {
            thatfirst = thatIter.next();
        }

        if (thisfirst == null) {
            if (thatfirst == null) {
                // we are both empty, and rank the same
                return 0;
            }
            // i am empty, he is not so we are greater
            return 1;
        }

        if (thatfirst == null) {
            // he is empty, we are not so he is greater
            return -1;
        }

        return thisfirst.getName().compareTo(thatfirst.getName());
    }

    @Override
    public AbstractKeyList clone() {
        AbstractKeyList clone = null;
        try {
            clone = (AbstractKeyList) super.clone();
        } catch (CloneNotSupportedException e) {
            assert false : e;
        }
        return clone;
    }

    /**
     * The <code>NameVisitor</code> constructs a readable representation of the
     * Passage.
     */
    static class NameVisitor extends DefaultKeyVisitor {
        /**
         * Create a <code>NameVisitor</code>.
         */
        public NameVisitor() {
            buffer = new StringBuilder();
        }

        @Override
        public void visitLeaf(Key key) {
            buffer.append(key.getName());
            buffer.append(AbstractPassage.REF_PREF_DELIM);
        }

        @Override
        public String toString() {
            String reply = buffer.toString();
            if (reply.length() > 0) {
                // strip off the final ", "
                reply = reply.substring(0, reply.length() - AbstractPassage.REF_PREF_DELIM.length());
            }

            return reply;
        }

        protected StringBuilder buffer;
    }

    /**
     * The <code>OsisRefVisitor</code> constructs a readable representation of
     * the Passage, using OSIS names.
     */
    static class OsisRefVisitor extends NameVisitor {
        @Override
        public void visitLeaf(Key key) {
            buffer.append(key.getOsisRef());
            buffer.append(AbstractPassage.REF_PREF_DELIM);
        }
    }

    /**
     * The <code>OsisRefVisitor</code> constructs a readable representation of
     * the Passage, using OSIS names.
     */
    static class OsisIDVisitor extends NameVisitor {
       @Override
        public void visitLeaf(Key key) {
            buffer.append(key.getOsisID());
            buffer.append(AbstractPassage.REF_OSIS_DELIM);
        }

        @Override
        public String toString() {
            String reply = super.toString();
            if (reply.length() > 0) {
                // strip off the final " "
                reply = reply.substring(0, reply.length() - AbstractPassage.REF_OSIS_DELIM.length());
            }

            return reply;
        }
    }

    /**
     * The common user visible name for this work
     */
    private String name;

    /**
     * Serialization ID
     */
    private static final long serialVersionUID = 3858640507828137034L;
}
