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

#include "group.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 Wdg::Pad_Proxy
{

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

Group::~Group ()
{
  clear_columns ();
}

void
Group::set_pad ( QObject * pad_n )
{
  _pad = pad_n;
}

void
Group::set_group_index ( unsigned int idx_n )
{
  _group_index = idx_n;
}

void
Group::set_group_id ( const QString & id_n )
{
  _group_id = id_n;
}

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

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

void
Group::set_style_id ( unsigned int style_id_n )
{
  _style_id = style_id_n;
}

void
Group::clear_columns ()
{
  if ( !_columns.empty () ) {
    _columns.clear ();
    // Clear statistics
    _num_sliders = 0;
    _num_switches = 0;
  }
}

void
Group::append_column ( Column * column_n )
{
  if ( column_n != nullptr ) {
    column_n->setParent ( this );
    column_n->set_column_index ( _columns.size () );

    _columns.emplace_back ( column_n );
    if ( column_n->has_slider () ) {
      ++_num_sliders;
    }
    if ( column_n->has_switch () ) {
      ++_num_switches;
    }
  }
}

bool
Group::set_focus ( unsigned int column_n, unsigned int row_n )
{
  bool success = false;
  if ( column_n >= num_columns () ) {
    // Use first column as fallback
    column_n = 0;
  }
  if ( column_n < num_columns () ) {
    success = column ( column_n )->set_focus ( row_n );
  }
  return success;
}

bool
Group::event ( QEvent * event_n )
{
  if ( event_n->type () == Wdg::evt_pass_event_focus ) {
    Wdg::Pass_Event_Focus * ev_fp =
        static_cast< Wdg::Pass_Event_Focus * > ( event_n );

    _focus_column = ev_fp->column_idx;
    _focus_row = ev_fp->row_idx;
    _has_focus = ev_fp->ev_focus.gotFocus ();

    if ( pad () != nullptr ) {
      ev_fp->group_idx = group_index ();
      QCoreApplication::sendEvent ( pad (), event_n );
    }
    return true;
  }

  return QObject::event ( event_n );
}

} // namespace Wdg::Pad_Proxy
