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

#include "group.hpp"
#include "qsnd/mixer/elem.hpp"
#include "wdg/event_types.hpp"
#include "wdg/pad_proxy/column.hpp"
#include "wdg/pad_proxy/slider.hpp"
#include "wdg/pad_proxy/switch.hpp"
#include "wdg/pass_events.hpp"
#include <QCoreApplication>
#include <iostream>

namespace MWdg::Mixer::Sliders::Proxy
{

Group::Group ( QObject * parent_n )
: MWdg::Mixer::Proxy::Group ( parent_n )
{
}

Group::~Group () = default;

bool
Group::should_be_separated () const
{
  QSnd::Mixer::Elem * qsme = qsnd_mixer_elem ();
  if ( qsme != nullptr ) {
    if ( ( qsme->num_volume_channels ( snd_dir () ) > 1 ) &&
         !qsme->volumes_equal ( snd_dir () ) ) {
      return true;
    }
    if ( ( qsme->num_switch_channels ( snd_dir () ) > 1 ) &&
         !qsme->switches_equal ( snd_dir () ) ) {
      return true;
    }
  }
  return false;
}

bool
Group::event ( QEvent * event_n )
{
  if ( event_n->type () == Wdg::evt_pass_event_key ) {
    Wdg::Pass_Event_Key * ev_kp =
        static_cast< Wdg::Pass_Event_Key * > ( event_n );
    if ( ev_kp->column_idx < num_columns () ) {
      Wdg::Pad_Proxy::Column * pcol = column ( ev_kp->column_idx );
      // Pass the key event to the switch widget
      Wdg::Pad_Proxy::Slider * psl = pcol->slider_proxy ();
      if ( psl != nullptr ) {
        Wdg::Pad_Proxy::Switch * psw = pcol->switch_proxy ();
        // Use joined switch on demand
        if ( psw == nullptr ) {
          Wdg::Pad_Proxy::Column * col0 = column ( 0 );
          psw = col0->switch_proxy ();
        }
        if ( psw != nullptr ) {
          // Pass event to switch widget
          if ( psw->widget () != nullptr ) {
            const bool old_focus = psw->has_focus ();
            psw->set_has_focus ( psl->has_focus () );
            QCoreApplication::sendEvent ( psw->widget (), &ev_kp->ev_key );
            psw->set_has_focus ( old_focus );
          }
        }
      }
    }
    return true;
  }

  return MWdg::Mixer::Proxy::Group::event ( event_n );
}

} // namespace MWdg::Mixer::Sliders::Proxy
