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

#include "icon.hpp"
#include <QAction>
#include <QEvent>
#include <QIcon>
#include <QWheelEvent>
#include <iostream>

namespace Tray
{

Icon::Icon ( const Shared & shared_n, QObject * parent_n )
: QSystemTrayIcon ( parent_n )
, _shared ( shared_n )
{
  setToolTip ( _shared.application_title );

  connect ( this,
            SIGNAL ( activated ( QSystemTrayIcon::ActivationReason ) ),
            this,
            SLOT ( activation ( QSystemTrayIcon::ActivationReason ) ) );

  // Context menu
  {
    QAction * act_show ( new QAction ( this ) );
    act_show->setText ( tr ( "&Show mixer" ) );
    act_show->setShortcut ( QKeySequence ( tr ( "Ctrl+s" ) ) );
    act_show->setIcon ( QIcon::fromTheme ( "view-fullscreen" ) );
    connect ( act_show, &QAction::triggered, this, &Icon::sig_activated );

    QAction * act_quit ( new QAction ( this ) );
    //: %1 will be replaced with the program title
    act_quit->setText ( tr ( "&Close %1" ).arg ( _shared.application_title ) );
    act_quit->setShortcut ( QKeySequence ( QKeySequence::Quit ) );
    act_quit->setIcon ( QIcon::fromTheme ( "application-exit" ) );
    connect ( act_quit, &QAction::triggered, this, &Icon::sig_quit );

    _cmenu.addAction ( act_show );
    _cmenu.addAction ( act_quit );

    setContextMenu ( &_cmenu );
  }

  // Initialize icon
  setIcon ( _shared.volume_icons[ _icon_index ] );
}

Icon::~Icon () = default;

void
Icon::update_icon ()
{
  if ( _icon_index != _shared.volume.icon_index ) {
    _icon_index = _shared.volume.icon_index;
    setIcon ( _shared.volume_icons[ _icon_index ] );
  }
}

void
Icon::activation ( QSystemTrayIcon::ActivationReason reason_n )
{
  // std::cout << "Tray::Mixer::activation " << reason_n << "\n";

  if ( reason_n == QSystemTrayIcon::Context ) {
    return;
  } else if ( reason_n == QSystemTrayIcon::MiddleClick ) {
    Q_EMIT sig_middle_click ();
  } else {
    Q_EMIT sig_activated ();
  }
}

bool
Icon::event ( QEvent * event_n )
{
  // std::cout << "Tray::Icon::event: " << event_n->type() << "\n";

  bool res = QSystemTrayIcon::event ( event_n );

  switch ( event_n->type () ) {
  case QEvent::Wheel: {
    QWheelEvent * wev ( static_cast< QWheelEvent * > ( event_n ) );
    Q_EMIT sig_wheel_delta ( wev->angleDelta ().y () );
    res = true;
  } break;
  case QEvent::ToolTip:
    Q_EMIT sig_hover ();
    break;
  default:
    break;
  }

  return res;
}

} // namespace Tray
