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

#include "proxy.hpp"
#include "wdg/pad_proxy/column.hpp"
#include "wdg/pad_proxy/style.hpp"
#include "wdg/pass_events.hpp"
#include <QCoreApplication>
#include <QFocusEvent>
#include <iostream>

namespace Wdg::Pad_Proxy
{

Proxy::Proxy ( QObject * parent_n )
: QObject ( parent_n )
{
}

Proxy::~Proxy () = default;

Column *
Proxy::column () const
{
  Column * res ( nullptr );
  QObject * par = parent ();
  if ( par != nullptr ) {
    res = dynamic_cast< Column * > ( par );
  }
  return res;
}

Group *
Proxy::group () const
{
  Group * res = nullptr;
  Column * col = column ();
  if ( col != nullptr ) {
    res = col->group ();
  }
  return res;
}

void
Proxy::set_index ( unsigned char idx_n )
{
  _index = idx_n;
}

void
Proxy::set_has_focus ( bool flag_n )
{
  _has_focus = flag_n;
}

void
Proxy::set_enabled ( bool flag_n )
{
  if ( flag_n != is_enabled () ) {
    _is_enabled = flag_n;
    Q_EMIT sig_enabled_changed ( is_enabled () );
  }
}

void
Proxy::set_widget ( QWidget * wdg_n )
{
  if ( _widget != nullptr ) {
    _widget->removeEventFilter ( this );
  }

  _widget = wdg_n;

  if ( _widget != nullptr ) {
    _widget->installEventFilter ( this );
  }
}

void
Proxy::set_item_name ( const QString & name_n )
{
  _item_name = name_n;
}

void
Proxy::set_group_name ( const QString & name_n )
{
  _group_name = name_n;
}

void
Proxy::set_tool_tip ( const QString & tip_n )
{
  _tool_tip = tip_n;
}

void
Proxy::set_variant_id ( unsigned int id_n )
{
  _variant_id = id_n;
}

void
Proxy::set_style_id ( unsigned int id_n )
{
  _style_id = id_n;
}

void
Proxy::set_style ( Style * style_n )
{
  _style.reset ( style_n );
}

void
Proxy::update_value_from_source ()
{
  // Dummy implementation does nothing
}

bool
Proxy::eventFilter ( QObject * obj_n, QEvent * event_n )
{
  bool res = QObject::eventFilter ( obj_n, event_n );
  if ( !res && ( ( event_n->type () == QEvent::FocusIn ) ||
                 ( event_n->type () == QEvent::FocusOut ) ) ) {
    QFocusEvent * ev_foc = static_cast< QFocusEvent * > ( event_n );
    _has_focus = ev_foc->gotFocus ();
    if ( parent () != nullptr ) {
      Wdg::Pass_Event_Focus ev_pass ( *ev_foc );
      ev_pass.row_idx = index ();
      QCoreApplication::sendEvent ( parent (), &ev_pass );
    }
  }
  return res;
}

} // namespace Wdg::Pad_Proxy
