#include <stdlib.h>

#include <qstring.h>

#include <kcmdlineargs.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kdebug.h>
#include <kuniqueapplication.h>
#include <kwin.h>
#include <kstartupinfo.h>
#include "kaddressbook.h"

class KAddressBookApp : public KUniqueApplication {
  public:
    KAddressBookApp() : mMainWin(0) {}

    int newInstance();

  private:
    KAddressBook *mMainWin;
};

int KAddressBookApp::newInstance()
{
  if (isRestored()) {
    // There can only be one main window
    if (KMainWindow::canBeRestored(1)) {
      mMainWin = new KAddressBook;
      mMainWin->show();
      mMainWin->restore(1);
    }
  } else {
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    QCString addrStr = args->getOption("addr");
    QCString uidStr = args->getOption("uid");
    QString addr;
    QString uid;
    if (!addrStr.isEmpty()) addr = QString::fromLocal8Bit(addrStr);
    if (!uidStr.isEmpty()) uid = QString::fromLocal8Bit(uidStr);

    
    if (args->isSet("editor-only")) {
      if (!mMainWin)
        mMainWin = new KAddressBook;
        KStartupInfo::appStarted();
        mMainWin->hide();
    } else {
      if (mMainWin) {
        if (mMainWin->isVisible())
          kdDebug() << "KAddressBook already running." << endl;
        else
          mMainWin->show();
      } else {
        mMainWin = new KAddressBook;
        mMainWin->show();
      }
    }
    //Can not see why anyone would pass both a uid and an email address, so I'll leave it that two contact editors will show if they do
    if (!addr.isEmpty()) mMainWin->addEmail(addr);
    if (!uid.isEmpty()) mMainWin->showContactEditor(uid);
  }

  return 0;
}

// the dummy argument is required, because KMail apparently sends an empty
// argument.
static KCmdLineOptions kmoptions[] =
{
  { "a", 0 , 0 },
  { "addr <email>", I18N_NOOP("Shows contact editor with given email address"), 0 },
  { "uid <uid>", I18N_NOOP("Shows contact editor with given uid"), 0 },
  { "editor-only", I18N_NOOP("Launches in editor only mode"), 0 },
  { "+[argument]", I18N_NOOP("dummy argument"), 0},
  { 0, 0, 0}
};

int main(int argc, char *argv[])
{
  KLocale::setMainCatalogue("kaddressbook");
  KAboutData about("kaddressbook", I18N_NOOP("KAddressBook"),
                   "3.0",
                   I18N_NOOP("The KDE Address Book"),
		   KAboutData::License_BSD,
                   I18N_NOOP("(c) 1997-2002, The KDE PIM Team"));
  about.addAuthor("Don Sanders",I18N_NOOP("Original author and maintainer"));
  about.addAuthor("Cornelius Schumacher",
                  I18N_NOOP("libkabc port, csv import/export"),
                  "schumacher@kde.org");
  about.addAuthor("Greg Stern", I18N_NOOP("DCOP interface"));
  about.addAuthor("Mark Westcott",I18N_NOOP("Contact pinning"));

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmoptions );
  KUniqueApplication::addCmdLineOptions();

  if (!KAddressBookApp::start()) exit(0);

  KAddressBookApp app;

  return app.exec();
}

