package org.argosdic.action.program;

import java.util.Iterator;

import org.argosdic.ArgosDic;
import org.argosdic.action.BaseAction;
import org.argosdic.dictionary.SearchHistory;
import org.eclipse.jface.action.IAction;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolItem;

/**
 * ForwardAction.java
 * 
 * @author Xavier Cho
 * @version $Revision: 1.6 $ $Date: 2003/10/12 10:49:23 $
 */
public class BackAction extends BaseAction {
    public BackAction(ArgosDic application) {
        super(application, IAction.AS_DROP_DOWN_MENU);

        setEnabled(false);
    }

    /**
	 * @see org.eclipse.jface.action.IAction#runWithEvent(org.eclipse.swt.widgets.Event)
	 */
    public void runWithEvent(Event event) {
        SearchHistory history = application.getSearchHistory();

        if (event.detail == SWT.ARROW) {
            Display display = Display.getCurrent();
            Shell shell = display.getActiveShell();

            Menu menu = new Menu(shell, SWT.POP_UP);

            int i = history.getCurrentIndex();
            Iterator it = history.getBackwardHistory().iterator();
            while (it.hasNext()) {
                String word = (String) it.next();

                MenuItem item = new MenuItem(menu, SWT.PUSH);
                item.setText(word);

                item.addListener(SWT.Selection, new MenuItemListener(--i));
            }

            if (event.widget instanceof ToolItem) {
                ToolItem button = (ToolItem) event.widget;

                Rectangle bounds = button.getBounds();
                Point location = new Point(bounds.x, bounds.y + bounds.height);

                location = button.getParent().toDisplay(location);

                menu.setLocation(location);
            }

            menu.setVisible(true);
        } else {
            String word = history.back();
            if (word != null) {
                application.search(word, false);
            }
        }
    }

    private class MenuItemListener implements Listener {
        private int index;

        private MenuItemListener(int index) {
            this.index = index;
        }

        public void handleEvent(Event event) {
            SearchHistory history = application.getSearchHistory();
            String word = history.go(index);

            application.search(word, false);
        }
    }
}
