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

#include "desktop_items.hpp"
#include "init_globals.hpp"
#include "qastools_config.hpp"
#include "views/view_utility.hpp"
#include <QApplication>
#include <QString>
#include <iostream>

/// @brief The main function
///
int
main ( int argc, char * argv[] )
{
  init_globals ();

  // Qt Application
  QApplication app ( argc, argv );
  app.setOrganizationName ( QString ( PACKAGE_NAME ).toLower () );
  app.setApplicationName ( QString ( PROGRAM_NAME ).toLower () );
  app.setQuitOnLastWindowClosed ( false );
  app.setAttribute ( Qt::AA_DontShowIconsInMenus, false );

  Desktop_Items ditems;

  // Parse remaining command line options
  {
    const int res = ditems.init_settings ( argc, argv );
    if ( res < 0 ) {
      return res;
    }
  }

  // Connect to DBus
  ditems.dbus_connect ();

  // If an other instance is running send a message to it and quit
  if ( ditems.cmd_opts ().start_single_instance ) {
    if ( !ditems.dbus_connected () ) {
      if ( ditems.dbus_notify_remote () ) {
        return 0;
      }
    }
  }

  // Connect application signals with desktop item manager
  QObject::connect ( &app,
                     &QApplication::commitDataRequest,
                     &ditems,
                     &Desktop_Items::commit_data );

  QObject::connect ( &app,
                     &QApplication::saveStateRequest,
                     &ditems,
                     &Desktop_Items::save_state );

  QObject::connect ( &ditems,
                     &Desktop_Items::sig_quit,
                     &app,
                     &QApplication::quit,
                     Qt::QueuedConnection );

  // Load application icon, translators
  Views::load_application_icon ( &app, "multimedia-volume-control" );
  Views::load_translators ( &app );

  // Start and restore session (on demand)
  ditems.start ( app.isSessionRestored () );

  return app.exec ();
}
