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

#pragma once

#include <QApplication>
#include <QLocalServer>
#include <QPointer>
#include <list>
#include <memory>

/// @brief Application with single instance support
///
class Single_Application : public QApplication
{
  Q_OBJECT

  public:
  // -- Construction

  Single_Application ( int & argc,
                       char * argv[],
                       const QString & unique_key_n = QString () );

  ~Single_Application ();

  // -- Unique key

  const QString &
  unique_key () const
  {
    return _unique_key;
  }

  bool
  set_unique_key ( const QString & unique_key_n );

  bool
  is_running () const
  {
    return _is_running;
  }

  // -- Message

  bool
  send_message ( const QString & msg_n );

  const QString
  latest_message () const
  {
    return _latest_message;
  }

  // -- Session management

  void
  commitData ( QSessionManager & manager_n );

  void
  saveState ( QSessionManager & manager_n );

  // -- Signals

  Q_SIGNAL
  void
  sig_message_available ( QString mesg_n );

  // -- Protected slots
  protected:
  Q_SLOT
  void
  new_client ();

  Q_SLOT
  void
  read_clients_data ();

  Q_SLOT
  void
  clear_dead_clients ();

  protected:
  // -- Protected methods

  void
  publish_message ( QByteArray & data_n );

  private:
  // -- Attributes
  bool _is_running = false;
  QString _unique_key;
  QString _com_key;
  QString _com_file;
  QString _latest_message;

  std::unique_ptr< QLocalServer > _local_server;

  struct Client
  {
    QPointer< QLocalSocket > socket;
    QByteArray data;
  };

  std::list< Client > _clients;

  const unsigned int _timeout = 2000;
};
