/*
 * File:     EAFMultipleFileResultViewer.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
 */

/* 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.search.result.viewer;

import mpi.eudico.client.annotator.ElanFrame2;

import mpi.eudico.client.annotator.grid.AnnotationTable;
import mpi.eudico.client.annotator.grid.GridViewerPopupMenu;

import mpi.eudico.client.util.LinkButton;

import mpi.search.content.result.model.ContentMatch;

import mpi.search.model.Match;
import mpi.search.model.Result;
import mpi.search.model.ResultEvent;

import mpi.search.viewer.AbstractResultViewer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


/**
 * $Id: EAFMultipleFileResultViewer.java,v 1.1 2005/08/09 13:00:35 klasal Exp $ $Author: klasal $
 * $Version$
 */
public class EAFMultipleFileResultViewer extends AbstractResultViewer {
    private AnnotationTable table;
    private EAFResultViewerTableModel dataModel;
    private ElanFrame2 elanFrame;
    private JPopupMenu popup;
    private LinkButton nextButton;
    private LinkButton previousButton;
    private int defaultChunkSize = 50;

    /**
     * Creates a new EAFMultipleFileResultViewer object.
     *
     * @param elanFrame DOCUMENT ME!
     */
    public EAFMultipleFileResultViewer(ElanFrame2 elanFrame) {
        this.elanFrame = elanFrame;
        dataModel = new EAFResultViewerTableModel();
        table = new AnnotationTable(dataModel);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        setLayout(new BorderLayout());
        table.setDefaultRenderer(Object.class,
            new EAFResultViewerGridRenderer(dataModel));
        table.updateLocale();

        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
        scrollPane.getViewport().setBackground(Color.white);
        add(scrollPane, BorderLayout.CENTER);
        popup = new GridViewerPopupMenu(table);
        setTableListener();
        makeControlPanel();
    }

    /**
     * DOCUMENT ME!
     *
     * @param columnName DOCUMENT ME!
     * @param visible DOCUMENT ME!
     */
    public void setColumnVisible(String columnName, boolean visible) {
        table.setColumnVisible(columnName, visible);
    }

    /**
     * DOCUMENT ME!
     *
     * @param list DOCUMENT ME!
     */
    public void setData(List list) {
        dataModel.updateAnnotations(list);
    }

    /**
     * Needed so components don't disappear when resizing the frame too small ??
     *
     * @return the preferred size
     */
    public Dimension getPreferredSize() {
        return table.getPreferredScrollableViewportSize();
    }

    /**
     * DOCUMENT ME!
     */
    public void reset() {
        super.reset();
        dataModel.setFiltering(false);
        setData(new ArrayList());
    }

    /**
     * DOCUMENT ME!
     *
     * @param e DOCUMENT ME!
     */
    public void resultChanged(ResultEvent e) {
        result = (Result) e.getSource();

        if (result.getMatchCount() == 0) {
            reset();
        } else {
            if (e.getType() == ResultEvent.MATCH_ADDED) {
                showMatch(result.getLastMatch());

                if ((lastShownMatch - firstShownMatch) < result.getChunkSize()) {
                    dataModel.setRestrictionInterval(new int[] {
                            1, result.getChunkSize()
                        });
                }
            } else if ((e.getType() == ResultEvent.STATUS_CHANGED) &&
                    ((result.getStatus() == Result.COMPLETE) ||
                    (result.getStatus() == Result.INTERRUPTED))) {
                for (int i = lastShownMatch; i < result.getMatchCount(); i++) {
                    dataModel.addAnnotation((ContentMatch) result.getMatch(i));
                }

                updateButtons();
            }
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @param match DOCUMENT ME!
     */
    public void showMatch(Match match) {
        lastShownMatch++;

        dataModel.addAnnotation((ContentMatch) match);

        if ((lastShownMatch - firstShownMatch + 1) == result.getChunkSize()) {
            updateButtons();
            controlPanel.setVisible(true);
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @param interval DOCUMENT ME!
     */
    public void showMatches(int[] interval) {
        dataModel.setRestrictionInterval(interval);
        firstShownMatch = interval[0];
        lastShownMatch = interval[1];
        updateButtons();
    }

    /**
     * DOCUMENT ME!
     *
     * @param result DOCUMENT ME!
     */
    public void showResult(Result result) {
        setData(result.getMatches());
        updateButtons();
    }

    /**
     * This method sets listeners for the table
     */
    protected void setTableListener() {
        ListSelectionModel rowSM = table.getSelectionModel();
        rowSM.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting() == false) {
                        return;
                    }

                    int selrow = table.getSelectedRow();

                    if (selrow < 0) {
                        return;
                    }

                    if (elanFrame != null) {
                        int fileColumn = dataModel.findColumn(EAFResultViewerTableModel.FILENAME);
                        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                        ElanFrame2 newElanFrame = elanFrame.getFrameFor((String) dataModel.getValueAt(
                                    selrow, fileColumn));
                        setCursor(Cursor.getPredefinedCursor(
                                Cursor.DEFAULT_CURSOR));

                        if (newElanFrame != null) {
                            ContentMatch match = ((ContentMatch) dataModel.getValueAt(selrow,
                                    dataModel.findColumn(
                                        EAFResultViewerTableModel.ANNOTATION)));

                            newElanFrame.getViewerManager().getSelection()
                                        .setSelection(match.getBeginTimeBoundary(),
                                match.getEndTimeBoundary());
                            newElanFrame.getViewerManager()
                                        .getMasterMediaPlayer().setMediaTime(match.getBeginTimeBoundary());

                            // HS 07 apr 2005            
                            newElanFrame.toFront();
                            SwingUtilities.windowForComponent(EAFMultipleFileResultViewer.this)
                                          .toFront();
                        }
                    }
                }
            });

        table.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    if (SwingUtilities.isRightMouseButton(e) ||
                            e.isPopupTrigger()) {
                        popup.show(EAFMultipleFileResultViewer.this, 100, 20);
                    }
                }
            });
    }

    /**
     * DOCUMENT ME!
     */
    protected void makeControlPanel() {
        previousButton = new LinkButton(previousAction);
        nextButton = new LinkButton(nextAction);
        previousButton.setVisible(false);
        nextButton.setVisible(false);

        controlPanel.setOpaque(false);
        controlPanel.setBorder(new EmptyBorder(0, 0, 0, 0));
        controlPanel.add(previousButton);
        controlPanel.add(currentLabel);
        controlPanel.add(nextButton);
        controlPanel.add(javax.swing.Box.createHorizontalGlue());
    }

    /**
     * DOCUMENT ME!
     */
    protected void updateButtons() {
        super.updateButtons();
        previousButton.setVisible(previousAction.isEnabled());
        nextButton.setVisible(nextAction.isEnabled());
        previousButton.setLabel(intervalToString(getPreviousInterval()));
        nextButton.setLabel(intervalToString(getNextInterval()));
        ((java.awt.Window) getTopLevelAncestor()).validate();
    }
}
