/* event_callbacks.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2011-2022 Ralf Hoffmann.
 * You can contact me at: ralf@boomerangsworld.de
 *   or http://www.boomerangsworld.de/worker
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "event_callbacks.hh"
#include <algorithm>

int EventCallbacks::fireCallbacks( const event_callback_type_t type )
{
    if ( m_callbacks.count( type ) > 0 ) {
        for ( std::list< RefCount< GenericCallback<void> > >::iterator it1 = m_callbacks[type].begin();
              it1 != m_callbacks[type].end();
              it1++ ) {
            (*it1)->callback();
        }
    }
    return 0;
}

int EventCallbacks::registerCallback( RefCount< GenericCallback<void> > cb,
                                      const event_callback_type_t type )
{
    m_callbacks[type].push_back( cb );
    return 0;
}

static bool tcmp( const RefCount<GenericCallback<void> > &cmp_entry,
                  const RefCount<GenericCallback<void> > &elem )
{
    if ( elem.get() == NULL || cmp_entry.get() == NULL ) return false;
    if ( elem.get() == cmp_entry.get() ) return true;
    return false;
}

int EventCallbacks::unregisterCallback( RefCount< GenericCallback<void> > cb )
{
    std::map< event_callback_type_t, std::list< RefCount< GenericCallback<void> > > >::iterator it1;
    std::list<RefCount<GenericCallback<void> > >::iterator it2;

    for ( it1 = m_callbacks.begin();
          it1 != m_callbacks.end();
          ++it1 ) {
        it2 = std::find_if( it1->second.begin(),
                            it1->second.end(),
                            [&cb]( auto &elem ) { return tcmp( cb, elem ); });
        if ( it2 != it1->second.end() ) {
            it1->second.erase( it2 );
        }
    }

    return 0;
}
