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

#include "group.hpp"
#include "mwdg/mixer/proxy/column.hpp"
#include "qsnd/mixer/elem.hpp"
#include <iostream>

namespace MWdg::Mixer::Proxy
{

Group::Group ( QObject * parent_n )
: Wdg::Pad_Proxy::Group ( parent_n )
{
  // Separation timer
  _separation_timer.setSingleShot ( true );
  _separation_timer.setInterval ( 550 );
  connect ( &_separation_timer,
            &QTimer::timeout,
            this,
            &Group::timer_separation_check );
}

Group::~Group () = default;

void
Group::set_qsnd_mixer_elem ( QSnd::Mixer::Elem * qsme_n )
{
  if ( qsnd_mixer_elem () != nullptr ) {
    disconnect ( qsnd_mixer_elem (), 0, this, 0 );
  }

  _qsnd_mixer_elem = qsme_n;

  if ( qsnd_mixer_elem () != nullptr ) {
    connect ( qsnd_mixer_elem (),
              &QSnd::Mixer::Elem::sig_values_changed,
              this,
              &Group::update_mixer_values );
  }
}

void
Group::set_snd_dir ( unsigned char dir_n )
{
  _snd_dir = dir_n;
}

void
Group::set_is_joined ( bool flag_n )
{
  _is_joined = flag_n;
}

void
Group::set_is_visible ( bool flag_n )
{
  _is_visible = flag_n;
}

void
Group::set_separation_request ( bool flag_n )
{
  _separation_request = flag_n;
}

bool
Group::can_be_separated () const
{
  if ( qsnd_mixer_elem () != nullptr ) {
    return ( qsnd_mixer_elem ()->num_channels ( snd_dir () ) > 1 );
  }
  return false;
}

bool
Group::needs_separation () const
{
  return ( is_joined () && this->should_be_separated () );
}

void
Group::update_mixer_values ()
{
  for ( std::size_t ii = 0; ii < num_columns (); ++ii ) {
    static_cast< Column * > ( column ( ii ) )->update_mixer_values ();
  }

  // Check for needed separation
  if ( needs_separation () ) {
    if ( !_separation_timer.isActive () ) {
      _separation_timer.start ();
    }
  } else {
    if ( _separation_timer.isActive () ) {
      _separation_timer.stop ();
    }
  }

  // Notify parent on demand
  Q_EMIT sig_value_change ();
}

void
Group::timer_separation_check ()
{
  // std::cout << "Group::timer_separation_check\n";

  if ( needs_separation () ) {
    set_separation_request ( true );
    Q_EMIT sig_separation_requested ();
  }
}

} // namespace MWdg::Mixer::Proxy
