/*
 * File:     AbstractAnnotation.java
 * Project:  MPI Linguistic Application
 * Date:     03 April 2006
 *
 * Copyright (C) 2001-2006  Max Planck Institute for Psycholinguistics
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package mpi.eudico.server.corpora.clomimpl.abstr;

import mpi.eudico.server.corpora.clom.Annotation;
import mpi.eudico.server.corpora.clom.Tier;

import mpi.eudico.server.corpora.util.ACMEditEvent;
import mpi.eudico.server.corpora.util.ACMEditableObject;
import mpi.eudico.server.corpora.util.ParentAnnotationListener;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.Iterator;
import java.util.Vector;


/**
 * DOCUMENT ME!
 * $Id: AbstractAnnotation.java,v 1.5 2005/12/29 15:57:22 klasal Exp $
 * @author $Author: klasal $
 * @version $Revision: 1.5 $
 */
public abstract class AbstractAnnotation implements Annotation {
    private Tier tier;
    private String value = "";
    private String id = null;
    private boolean markedDeleted = false;
    private ArrayList parentAnnotListeners;

    /**
     * Creates a new AbstractAnnotation instance
     */
    public AbstractAnnotation() {
        parentAnnotListeners = new ArrayList();
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public abstract long getBeginTimeBoundary();

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public abstract long getEndTimeBoundary();

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public String getValue() {
        return value;
    }

    /**
     * DOCUMENT ME!
     *
     * @param theValue DOCUMENT ME!
     */
    public void setValue(String theValue) {
        value = theValue;

        modified(ACMEditEvent.CHANGE_ANNOTATION_VALUE, null);
    }

    public String getId() {
        return id;
    }

    public void setId(String s) {
        id = s;
    }

    /**
     * DOCUMENT ME!
     *
     * @param theValue DOCUMENT ME!
     */
    public void updateValue(String theValue) {
        value = theValue;

        modified(ACMEditEvent.CHANGE_ANNOTATION_VALUE, null);
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public Tier getTier() {
        return tier;
    }

    /**
     * DOCUMENT ME!
     *
     * @param theTier DOCUMENT ME!
     */
    protected void setTier(Tier theTier) {
        tier = theTier;
    }

    /**
     * DOCUMENT ME!
     *
     * @param deleted DOCUMENT ME!
     */
    public void markDeleted(boolean deleted) {
        // System.out.println("ann: " + getValue() + " marked deleted");
        markedDeleted = deleted;

        notifyParentListeners();
        unregisterWithParent();
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public boolean isMarkedDeleted() {
        return markedDeleted;
    }

    /**
     * DOCUMENT ME!
     */
    public void unregisterWithParent() {
        if (hasParentAnnotation()) {
            Annotation p = getParentAnnotation();

            if (p != null) {
                p.removeParentAnnotationListener(this);
            }
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @param operation DOCUMENT ME!
     * @param modification DOCUMENT ME!
     *
     */
    public void modified(int operation, Object modification) {
        handleModification(this, operation, modification);
    }

    /**
     * DOCUMENT ME!
     *
     * @param source DOCUMENT ME!
     * @param operation DOCUMENT ME!
     * @param modification DOCUMENT ME!
     */
    public void handleModification(ACMEditableObject source, int operation,
        Object modification) {
        if (tier != null) {
            tier.handleModification(source, operation, modification);
        }
    }

    /**
     * MK:02/07/03 <br>
     * Each Annotation has 0..n  ACMListeners. Children of this annotation do
     * not account as ACMListeners.
     *
     * @param l DOCUMENT ME!
     */

    //	public ArrayList getListeners() {
    //		return listeners;
    //	}
    public void addParentAnnotationListener(ParentAnnotationListener l) {
        if (!parentAnnotListeners.contains(l)) {
            parentAnnotListeners.add(l);
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @param l DOCUMENT ME!
     */
    public void removeParentAnnotationListener(ParentAnnotationListener l) {
        parentAnnotListeners.remove(l);
    }

    /**
     * DOCUMENT ME!
     */
    public void notifyParentListeners() {
        ArrayList copiedList = new ArrayList(parentAnnotListeners);
        Iterator i = copiedList.iterator();

        while (i.hasNext()) {
            ParentAnnotationListener listener = (ParentAnnotationListener) i.next();
            listener.parentAnnotationChanged(new EventObject(this));
        }
    }

    /**
     * MK:02/07/03 <br>
     * Each Annotation has 0..n  children-Annotations, for Transcriptions, a
     * morpheme brake (MB) may have several part of speeches (PS).  The PS are
     * children annotations of MB.<br>
     * (Name hint: children listen to their parent, so they are
     * parent-listeners.)
     *
     * @return children-Annotations of 'this' parent, or empty ArrayList.
     */
    public ArrayList getParentListeners() {
        return parentAnnotListeners;
    }

    /**
     * AK:05/07/2002 <br>
     * gets a Vector with all dependent children on the specified tier If
     * there are no children, an empty vector is returned
     *
     * @param tier
     *
     * @return Vector of Annotations
     */
    public final Vector getChildrenOnTier(Tier tier) {
        Vector children = new Vector();
        Annotation annotation = null;

        for (Iterator it = parentAnnotListeners.iterator(); it.hasNext();) {
            annotation = (Annotation) it.next();

            if (annotation.getTier() == tier) {
                children.add(annotation);
            }
        }

        return children;
    }

    // Comparable interface method
    public int compareTo(Object obj) {
        // if not both RefAnnotations, delegate comparison to first alignable root.
        // if both RefAnnotations, call compareRefAnnotations()
        int ret = 0;

        Annotation a1 = this;
        Annotation a2 = (Annotation) obj;

        // comparison is on basis of embedding in 'network' of Annotations. When an Annotation
        // is marked deleted, it is already detached from the network.
        if (a1.isMarkedDeleted() || a2.isMarkedDeleted()) {
            return compareOtherwise(a1, a2);
        }

        int numOfRefAnnotations = 0;

        if (this instanceof RefAnnotation) {
            numOfRefAnnotations += 1;
            a1 = ((RefAnnotation) this).getFirstAlignableRoot();
        }

        if (obj instanceof RefAnnotation) {
            numOfRefAnnotations += 1;
            a2 = ((RefAnnotation) obj).getFirstAlignableRoot();
        }

        if (a1 != a2) { // two different RefAnnotations can have same alignable parent         
            ret = ((AlignableAnnotation) a1).getBegin().compareTo(((AlignableAnnotation) a2).getBegin());

            if (ret == 0) {
                ret = -1;
            }

            // otherwise shared begin timeslot would lead to equality
        } else { // same alignable parent

            // if one Alignable and one RefAnnotation, the Alignable one comes before the Ref one
            if (numOfRefAnnotations == 1) {
                if (this instanceof AlignableAnnotation) {
                    ret = -1;
                } else {
                    ret = 1;
                }
            } else if (numOfRefAnnotations == 2) { // two RefAnnotations with the same parent. 
                ret = compareRefAnnotations((RefAnnotation) this,
                        (RefAnnotation) obj);
            }
        }

        return ret;
    }

    private int compareOtherwise(Annotation a1, Annotation a2) {
        if (a1.equals(a2)) {
            return 0;
        } else {
            // no refs to parents, fall back on index on Tier
            Tier t1 = a1.getTier();
            Tier t2 = a2.getTier();

            if (t1 == t2) {
                Vector v = null;

                v = ((TierImpl) t1).getAnnotations();

                if (v.indexOf(a1) < v.indexOf(a2)) {
                    return -1;
                } else {
                    return 1;
                }
            } else {
                return -1;
            }
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @param a1 DOCUMENT ME!
     * @param a2 DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public int compareRefAnnotations(RefAnnotation a1, RefAnnotation a2) {
        // if on same tier, compare via "chain of reference".
        // else, take first and go up reference tree until on same tier or until alignable parent,
        // take second and repeat
        int ret = 0;

        if ((a1.getTier() == a2.getTier()) &&
                (a1.getReferences().firstElement() == a2.getReferences()
                                                            .firstElement())) { // and have same parent
            ret = compareUsingRefChain(a1, a2);
        } else {
            Annotation parent = (Annotation) (a1.getReferences().firstElement());

            if (parent instanceof RefAnnotation) {
                ret = compareRefAnnotations((RefAnnotation) parent, a2);
            }

            if (ret == 0) { // still undecided
                parent = (Annotation) (a2.getReferences().firstElement());

                if (parent instanceof RefAnnotation) {
                    ret = compareRefAnnotations(a1, (RefAnnotation) parent);
                }
            }
        }

        return ret;
    }

    /**
     * DOCUMENT ME!
     *
     * @param a1 DOCUMENT ME!
     * @param a2 DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public int compareUsingRefChain(RefAnnotation a1, RefAnnotation a2) {
        // a1 and a2 are on the same tier, and have the same alignable parent
        int ret = 1; // default: a1 comes before a2
        RefAnnotation nextR = a1.getNext();

        if (a1 == a2) {
            ret = 0;
        } else {
            while (nextR != null) {
                if (nextR == a2) { // a2 after a1
                    ret = -1;

                    break;
                }

                nextR = nextR.getNext();
            }
        }

        return ret;
    }
}
