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

#include "switch.hpp"
#include "qsnd/hctl/elem.hpp"
#include <iostream>

namespace MWdg::HCtl::Proxy
{

Switch::Switch ( QObject * parent_n )
: MWdg::HCtl::Proxy::Proxy ( parent_n )
, _switch_state ( false )
, _updating_state ( false )
{
}

Switch::~Switch () = default;

void
Switch::set_switch_state ( bool state_n )
{
  if ( switch_state () != state_n ) {
    _switch_state = state_n;
    this->switch_state_changed ();
    Q_EMIT sig_switch_state_changed ( switch_state () );
  }
}

void
Switch::switch_state_changed ()
{
  if ( ( snd_elem () != nullptr ) && ( snd_elem ()->is_writable () ) &&
       !_updating_state ) {
    if ( is_joined () || joined_by_key () ) {
      snd_elem ()->set_switch_all ( switch_state () );
    } else {
      snd_elem ()->set_switch_state ( elem_idx (), switch_state () );
    }
  }
}

void
Switch::update_value_from_source ()
{
  if ( ( snd_elem () != nullptr ) && !_updating_state ) {
    _updating_state = true;
    set_switch_state ( snd_elem ()->switch_state ( elem_idx () ) );
    _updating_state = false;
  }
}

} // namespace MWdg::HCtl::Proxy
