/*
 *  PHEX - The pure-java Gnutella-servent.
 *  Copyright (C) 2001 - 2006 Phex Development Group
 *
 *  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
 * 
 *  Created on 07.02.2006
 *  --- CVS Information ---
 *  $Id: SearchButtonBar.java 3638 2006-12-01 10:14:16Z GregorK $
 */
package phex.gui.tabs.search;

import java.awt.event.*;
import java.util.HashMap;
import java.util.Iterator;

import javax.swing.*;

import phex.event.SearchListChangeListener;
import phex.gui.common.FWButtonBar;
import phex.gui.tabs.search.cp.SearchInfoBox;
import phex.query.QueryManager;
import phex.query.Search;
import phex.query.SearchContainer;
import phex.utils.NLogger;
import phex.utils.NLoggerNames;

public class SearchButtonBar extends FWButtonBar implements SearchListChangeListener
{
    private Timer updateDisplayTimer;
    private SearchTab searchTab;
    private SearchResultsDataModel displayedDataModel;
    private SearchContainer searchContainer;
    private ButtonGroup searchButtonGroup;
    private Object accessLock = new Object();
    /**
     * This button is used in the button group to indicate nothing is selected.
     */
    private AbstractButton notSelectedButton;
    private HashMap searchButtonMap;
    private ButtonHandler buttonHandler;
    
    public SearchButtonBar( SearchTab searchTab )
    {
        super();
        this.searchTab = searchTab;
        
        searchButtonGroup = new ButtonGroup();
        notSelectedButton = new JToggleButton();
        searchButtonGroup.add(notSelectedButton);
        
        searchButtonMap = new HashMap();
        buttonHandler = new ButtonHandler();
        searchContainer = QueryManager.getInstance().getSearchContainer();
        int count = searchContainer.getSearchCount();
        for ( int i = 0; i < count; i++ )
        {
            Search search = searchContainer.getSearchAt(i);
            if ( search != null )
            {
                searchAdded(search, -1);
            }
        }
        addMouseListener( new MouseListener());
    }
    
    public void addNotify()
    {
        super.addNotify();
        searchContainer.addSearchListChangeListener( this );
        if ( updateDisplayTimer == null )
        {
            updateDisplayTimer = new Timer( 2000, new UpdateButtonsTimerAction());
        }
        updateDisplayTimer.start();
    }
    
    public void removeNotify()
    {
        super.removeNotify();
        searchContainer.removeSearchListChangeListener( this );
        if( updateDisplayTimer != null )
        {
            updateDisplayTimer.stop();
            updateDisplayTimer = null;
        }
    }
    
    public void setDisplayedSearch( SearchResultsDataModel searchResultsDataModel )
    {
        if ( displayedDataModel != searchResultsDataModel )
        {
            displayedDataModel = searchResultsDataModel;
            if ( searchResultsDataModel != null )
            {
                Search search = searchResultsDataModel.getSearch();
                SearchButton btn = (SearchButton) searchButtonMap.get(search);
                if ( btn != null )
                {// button might not be available yet since its created delayed on 
                 // event thread.
                    btn.setSelected(true);
                }
            }
            else
            {
                notSelectedButton.setSelected(true);
            }
        }
    }

    public void searchChanged( int position )
    {
    }

    public void searchAdded( Search search, int position )
    {
        SearchButton btn = new SearchButton( search, searchTab );
        btn.addActionListener( buttonHandler );
        
        synchronized ( accessLock )
        {
            searchButtonMap.put(search, btn);
            searchButtonGroup.add(btn);
            addButton( btn );
        }
        
        if ( displayedDataModel != null && search == displayedDataModel.getSearch() )
        {// select the button of the displayed model
            btn.setSelected(true);
        }
    }

    public void searchRemoved( Search search, int position )
    {
        SearchButton btn = (SearchButton) searchButtonMap.remove(search);
        synchronized ( accessLock )
        {
            searchButtonGroup.remove( btn );
            removeButton( btn );
        }
    }
    
    private final class MouseListener extends MouseAdapter
    {
        public void mouseClicked( MouseEvent e )
        {
            try
            {
                if (e.getClickCount() == 2)
                {
                    // handle double click as new search request
                    searchTab.setDisplayedSearch( null );
                }
            }
            catch (Throwable th)
            {
                NLogger.error(NLoggerNames.USER_INTERFACE, th, th);
            }
        }
    }

    private final class UpdateButtonsTimerAction implements ActionListener
    {
        public void actionPerformed( ActionEvent e )
        {
            try
            {
                synchronized ( accessLock )
                {
                    Iterator iterator = buttons.iterator();
                    while( iterator.hasNext() )
                    {
                        SearchButton searchButton = (SearchButton)iterator.next();
                        searchButton.updateButtonDisplay();
                    }
                }
            }
            catch ( Throwable th )
            {
                NLogger.error(SearchInfoBox.class, th, th);
            }
        }
    }

    private class ButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            try
            {
                SearchButton searchButton = ((SearchButton)e.getSource());
                
                searchButton.updateButtonDisplay();
                searchTab.refreshTabActions();
                Search search = searchButton.getSearch();
                if ( search == null )
                {
                    return;
                }
                SearchResultsDataModel dataModel = SearchResultsDataModel.lookupResultDataModel( search );
                searchTab.setDisplayedSearch( dataModel );
            }
            catch ( Exception exp)
            {// catch all handler
                NLogger.error( NLoggerNames.USER_INTERFACE, exp, exp );
            }
        }
    }
}
