/*
 * File:     AnnotationUpCA.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.client.annotator.commands;

import mpi.eudico.client.annotator.ElanLocale;
import mpi.eudico.client.annotator.ViewerManager2;

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

import mpi.eudico.server.corpora.clomimpl.abstr.TierImpl;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import java.util.Vector;

import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.KeyStroke;


/**
 * DOCUMENT ME!
 * $Id: AnnotationUpCA.java,v 1.1 2005/08/03 14:59:36 hasloe Exp $
 * @author $Author: hasloe $
 * @version $Revision: 1.1 $
 */
public class AnnotationUpCA extends CommandAction {
    private Icon icon;

    /**
     * Creates a new AnnotationUpCA instance
     *
     * @param theVM DOCUMENT ME!
     */
    public AnnotationUpCA(ViewerManager2 theVM) {
        super(theVM, ELANCommandFactory.ANNOTATION_UP);

        icon = new ImageIcon(this.getClass().getResource("/mpi/eudico/client/annotator/resources/GoToUpperAnnotation.gif"));
        putValue(SMALL_ICON, icon);
        putValue(SHORT_DESCRIPTION,
            ElanLocale.getString(ELANCommandFactory.ANNOTATION_UP + "ToolTip"));
        putValue(Action.ACCELERATOR_KEY,
            KeyStroke.getKeyStroke(KeyEvent.VK_UP, ActionEvent.ALT_MASK));
        putValue(Action.NAME, "");
        putValue(DEFAULT, "ANNOTATION_UP");
    }

    /**
     * DOCUMENT ME!
     */
    protected void newCommand() {
        command = ELANCommandFactory.createCommand(vm.getTranscription(),
                ELANCommandFactory.ACTIVE_ANNOTATION);
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    protected Object getReceiver() {
        return vm;
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    protected Object[] getArguments() {
        Annotation currentActiveAnnot = vm.getActiveAnnotation().getAnnotation();
        Annotation newActiveAnnot = null;
        Vector visibleTiers = vm.getMultiTierControlPanel().getVisibleTiers();

        if (visibleTiers.size() == 0) {
            return new Object[] { currentActiveAnnot }; // do nothing
        }

        if (currentActiveAnnot != null) {
            long refTime;
            long mediaTime = vm.getMasterMediaPlayer().getMediaTime();

            if ((mediaTime >= currentActiveAnnot.getBeginTimeBoundary()) &&
                    (mediaTime <= currentActiveAnnot.getEndTimeBoundary())) {
                if (mediaTime == currentActiveAnnot.getBeginTimeBoundary()) {
                    // +1 because TierImpl.getAnnotationAtTime compares inclusive on both sides
                    refTime = mediaTime + 1;
                } else {
                    refTime = mediaTime;
                }
            } else {
                refTime = currentActiveAnnot.getBeginTimeBoundary() + 1;
            }

            TierImpl currentTier = (TierImpl) currentActiveAnnot.getTier();

            int index = visibleTiers.indexOf(currentTier);

            if ((index > 0) && (index <= (visibleTiers.size() - 1))) {
                // current tier is visible
                TierImpl upTier = getNextNonEmptyTier(index - 1);

                if (upTier == null) {
                    newActiveAnnot = currentActiveAnnot; // do nothing
                } else {
                    // get annotation before this time
                    newActiveAnnot = getAnnotationAtOrBefore(upTier, refTime);
                }
            } else if (index < 0) {
                // current tier not visible, start with the bottom tier or the active tier, or do nothing??
                TierImpl firstTier = getNextNonEmptyTier(visibleTiers.size() -
                        1);

                if (firstTier == null) {
                    newActiveAnnot = currentActiveAnnot;
                } else {
                    newActiveAnnot = getAnnotationAtOrBefore(firstTier, refTime);
                }
            } else if (index == 0) {
                // the active annotation is on the first visible tier, do nothing
                newActiveAnnot = currentActiveAnnot;
            }
        } else { // try on basis of current time and active tier

            Tier activeTier = vm.getMultiTierControlPanel().getActiveTier();

            if ((activeTier != null) &&
                    (((TierImpl) activeTier).getNumberOfAnnotations() > 0)) {
                newActiveAnnot = getAnnotationAtOrBefore((TierImpl) activeTier,
                        vm.getMasterMediaPlayer().getMediaTime());
            } else {
                // use last visible tier
                TierImpl lastTier = getNextNonEmptyTier(visibleTiers.size() -
                        1);

                if (lastTier == null) {
                    newActiveAnnot = currentActiveAnnot;
                } else {
                    newActiveAnnot = getAnnotationAtOrBefore(lastTier,
                            vm.getMasterMediaPlayer().getMediaTime());
                }
            }
        }

        Object[] args = new Object[1];
        args[0] = newActiveAnnot;

        return args;
    }

    /**
     * Finds the next tier (ascending) containing annotations.
     *
     * @param fromIndex the index to start searching from (inclusive)
     *
     * @return the next tier or null
     */
    private TierImpl getNextNonEmptyTier(int fromIndex) {
        Vector vis = vm.getMultiTierControlPanel().getVisibleTiers();

        if (vis.size() == 0) {
            return null;
        }

        if ((fromIndex < 0) || (fromIndex >= vis.size())) {
            return null;
        }

        for (int i = fromIndex; i >= 0; i--) {
            if (((TierImpl) vis.get(i)).getNumberOfAnnotations() > 0) {
                return (TierImpl) vis.get(i);
            }
        }

        return null;
    }

    /**
     * If there is an annotation at the specified time return it, otherwise
     * return the closest annotation before this time
     *
     * @param tier the tier to search
     * @param time the reference time
     *
     * @return the annotation at or before the specified time
     */
    private Annotation getAnnotationAtOrBefore(final TierImpl tier,
        final long time) {
        if (tier.getAnnotationAtTime(time) != null) {
            return tier.getAnnotationAtTime(time);
        } else {
            return tier.getAnnotationBefore(time);
        }
    }
}
