#include "ksystraycmd.h"

#include <KAboutData>
#include <KShell>
#include <KAboutData>
#include <KLocalizedString>

#include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QDebug>
#include <QX11Info>

#include <X11/Xlib.h>
#include <fcntl.h>

int main( int argc, char *argv[] )
{
    QApplication app(argc, argv);

    KAboutData aboutData(QStringLiteral("ksystraycmd5"),
        xi18nc("@title", "<application>KSysTrayCmd</application>"),
        QStringLiteral("0.2"),
        xi18nc("@title", "Allows any application to be kept in the system tray"),
        KAboutLicense::GPL,
        xi18nc("@info:credit", "(C) 2001-2002 Richard Moore (rich@kde.org)"),
        QString(),
        QString());

    aboutData.setOrganizationDomain(QByteArray("kde.org"));
    aboutData.setProductName(QByteArray("ksystraycmd5"));

    aboutData.addAuthor(xi18nc("@info:credit", "Richard Moore"), QString(), QStringLiteral("rich@kde.org"));

    KAboutData::setApplicationData(aboutData);

    QCommandLineParser parser;

    parser.addPositionalArgument(QStringLiteral("command"),  i18n("Command to execute"));

    parser.addOption(QCommandLineOption(QStringLiteral("window"), i18n("A regular expression matching the window title\n"
        "If you do not specify one, then the very first window\n"
        "to appear will be taken - not recommended."), i18n("regexp")));
    parser.addOption(QCommandLineOption(QStringLiteral("wid"), i18n("The window id of the target window\n"
        "Specifies the id of the window to use. If the id starts with 0x\n"
        "it is assumed to be in hex."), i18n("int")));
    parser.addOption(QCommandLineOption(QStringLiteral("hidden"), i18n( "Hide the window to the tray on startup" )));
    parser.addOption(QCommandLineOption(QStringLiteral("startonshow"), i18n( "Wait until we are told to show the window before\n"
        "executing the command" )));
    parser.addOption(QCommandLineOption(QStringLiteral("tooltip"), i18n( "Sets the initial tooltip for the tray icon" ), QLatin1String("text")));
    parser.addOption(QCommandLineOption(QStringLiteral("keeprunning"), i18n( "Keep the tray icon even if the client exits. This option\n"
        "has no effect unless startonshow is specified." )));
    parser.addOption(QCommandLineOption(QStringLiteral("ownicon"), i18n( "Use ksystraycmd5's icon instead of the window's icon in the systray\n"
        "(should be used with --icon to specify ksystraycmd5 icon)" )));
    parser.addOption(QCommandLineOption(QStringLiteral("ontop"), i18n( "Try to keep the window above other windows")));
    parser.addOption(QCommandLineOption(QStringLiteral("quitonhide"), i18n( "Quit the client when we are told to hide the window.\n"
        "This has no effect unless startonshow is specified and implies keeprunning." )));
    /*options.add("menuitem <item>", ki18n( "Adds a custom entry to the tray icon menu\n"
        "The item should have the form text:command." ));*/

    parser.addHelpOption();
    parser.addVersionOption();

    aboutData.setupCommandLine(&parser);
    parser.process(app);
    aboutData.processCommandLine(&parser);

    app.setApplicationName(aboutData.componentName());
    app.setApplicationDisplayName(aboutData.displayName());
    app.setOrganizationDomain(aboutData.organizationDomain());
    app.setApplicationVersion(aboutData.version());

  //
  // Setup the tray icon from the arguments.
  //
  const QStringList &args = parser.positionalArguments();
  KSysTrayCmd cmd;

  // Read the window id
  QString wid = parser.value( "wid" );
  if ( !wid.isEmpty() ) {
      int base = 10;
      if ( wid.startsWith( "0x" ) ) {
	  base = 16;
	  wid = wid.right( wid.length() - 2 );
      }

      bool ok=true;
      ulong w = wid.toULong( &ok, base );
      if ( ok )
	  cmd.setTargetWindow( w );
      else {
	  qWarning() << "KSysTrayCmd: Got bad win id" ;
      }
  }

  // Read window title regexp
  QString title = parser.value( "window" );
  if ( !title.isEmpty() )
      cmd.setPattern( title );

// TODO FIXME KF5 port
//   if ( title.isEmpty() && wid.isEmpty() && (parser.positionalArguments().count() == 0) )
//     KCmdLineArgs::usageError(i18n("No command or window specified"));

  // Read the command
  QString command;
  for ( int i = 0; i < parser.positionalArguments().count(); i++ )
    command += KShell::quoteArg(args.at(i)) + ' ';
  if ( !command.isEmpty() )
      cmd.setCommand( command );

  // Tooltip
  QString tip = parser.value( "tooltip" );
  if ( !tip.isEmpty() )
    cmd.setDefaultTip( tip );

  // Apply icon and tooltip
  cmd.refresh();

  // Keep running flag
  if ( parser.isSet( "keeprunning" )  )
    cmd.setNoQuit( true );

  if ( parser.isSet( "quitonhide" ) ) {
    cmd.setNoQuit( true );
    cmd.setQuitOnHide( true );
  }

  // Start hidden
  if ( parser.isSet( "hidden" ) )
    cmd.hideWindow();

  // On top
  if ( parser.isSet( "ontop" ) )
    cmd.setOnTop(true);

  // Use ksystraycmd icon
  if ( parser.isSet( "ownicon" ) )
    cmd.setOwnIcon(true);

  // Lazy invocation flag
  if ( parser.isSet( "startonshow" ) ) {
    cmd.setStartOnShow( true );
    cmd.show();
  }
  else {
    if ( !cmd.start() )
      return 1;
  }

  fcntl(ConnectionNumber(QX11Info::display()), F_SETFD, 1);
  

  return app.exec();
}

