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

#include "switch.hpp"
#include <QApplication>
#include <QEvent>
#include <QKeyEvent>

namespace MWdg::Mixer::Switches::Proxy
{

Switch::Switch ()
: _qsnd_mixer_elem ( nullptr )
, _channel_idx ( 0 )
, _snd_dir ( 0 )
, _is_joined ( false )
, _alsa_updating ( false )
{
}

Switch::~Switch () = default;

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

void
Switch::set_channel_idx ( unsigned int idx_n )
{
  _channel_idx = idx_n;
}

void
Switch::set_qsnd_mixer_elem ( QSnd::Mixer::Elem * selem_n )
{
  _qsnd_mixer_elem = selem_n;
}

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

void
Switch::switch_state_changed ()
{
  // std::cout << "Switch::switch_state_changed " <<
  //  switch_state() << "\n";

  if ( ( qsnd_mixer_elem () != 0 ) && ( !_alsa_updating ) ) {
    bool key_mod (
        ( QApplication::keyboardModifiers () & Qt::ControlModifier ) != 0 );
    key_mod = ( key_mod && has_focus () );
    if ( is_joined () || key_mod ) {
      qsnd_mixer_elem ()->set_switch_all ( snd_dir (), switch_state () );
    } else {
      qsnd_mixer_elem ()->set_switch (
          snd_dir (), channel_idx (), switch_state () );
    }

    // std::cout << "Switch::switch_state_changed " <<
    //"done" << "\n";
  }
}

void
Switch::update_value_from_source ()
{
  if ( ( qsnd_mixer_elem () != 0 ) && ( !_alsa_updating ) ) {
    _alsa_updating = true;
    set_switch_state (
        qsnd_mixer_elem ()->switch_state ( snd_dir (), channel_idx () ) );
    _alsa_updating = false;
  }
}

bool
Switch::eventFilter ( QObject * obj_n, QEvent * event_n )
{
  bool res = Wdg::Pad_Proxy::Switch::eventFilter ( obj_n, event_n );
  if ( !res ) {
    if ( event_n->type () == QEvent::KeyPress ) {
      QKeyEvent * kev = static_cast< QKeyEvent * > ( event_n );
      if ( kev->key () == Qt::Key_VolumeMute ) {
        toggle_switch_state ();
        res = true;
      }
    }
  }
  return res;
}

} // namespace MWdg::Mixer::Switches::Proxy
