/// QasTools: Desktop toolset for the Linux sound system ALSA.
/// \copyright See COPYING file.

#include "name.hpp"
#include "qsnd/mixer/elem.hpp"
#include <iostream>

namespace QSnd::Mixer::Filters
{

Name::Name ( bool blacklist_n )
: _blacklist ( blacklist_n )
{
}

Name::~Name () = default;

void
Name::set_blacklist ( bool flag_n )
{
  _blacklist = flag_n;
}

void
Name::append_name ( const QString & name_n )
{
  _names.push_back ( name_n );
}

void
Name::append_names ( const std::vector< QString > & names_n )
{
  _names.insert ( _names.end (), names_n.cbegin (), names_n.cend () );
}

void
Name::filter ( Element_Vector & accept_n, Element_Vector & drop_n )
{
  if ( _names.empty () ) {
    return;
  }

  {
    auto ait = accept_n.begin ();
    while ( ait != accept_n.end () ) {
      bool match = false;
      if ( const auto & elem = *ait; elem ) {
        // Compare all names
        for ( std::size_t dii = 0; dii < _names.size (); ++dii ) {
          const QString & cmp_str = _names[ dii ];
          if ( QString::compare (
                   cmp_str, elem->elem_name (), Qt::CaseInsensitive ) == 0 ) {
            match = true;
          } else if ( QString::compare ( cmp_str,
                                         elem->display_name (),
                                         Qt::CaseInsensitive ) == 0 ) {
            match = true;
          }
          if ( match ) {
            break;
          }
        }
      }

      if ( match == blacklist () ) {
        // Drop element
        drop_n.push_back ( std::move ( *ait ) );
        ait = accept_n.erase ( ait );
      } else {
        ++ait;
      }
    }
  }
}

} // namespace QSnd::Mixer::Filters
