/****************************************************************************
**
** Copyright (C) 1999-2006 Tilo Riemer <riemer@crossvc.com>,
**                         Frank Hemer <frank@hemer.org>,
**                         Jose Hernandez <joseh@tesco.net>
**                         Helmut Koll <HelmutKoll@web.de>,
**                         Tom Mishima <tmishima@mail.at-m.or.jp>
**
**
**----------------------------------------------------------------------------
**
**----------------------------------------------------------------------------
**
** CrossVC is available under two different licenses:
**
** If CrossVC is linked against the GPLed version of Qt 
** CrossVC is released under the terms of GPL also.
**
** If CrossVC is linked against a nonGPLed version of Qt 
** CrossVC is released under the terms of the 
** CrossVC License for non-Unix platforms (CLNU)
**
**
** CrossVC License for non-Unix platforms (CLNU):
**
** Redistribution and use in binary form, without modification, 
** are permitted provided that the following conditions are met:
**
** 1. Redistributions in binary form must reproduce the above copyright
**    notice, this list of conditions and the following disclaimer in the
**    documentation and/or other materials provided with the distribution.
** 2. It is not permitted to distribute the binary package under a name
**    different than CrossVC.
** 3. The name of the authors may not be used to endorse or promote
**    products derived from this software without specific prior written
**    permission.
** 4. The source code is the creative property of the authors.
**    Extensions and development under the terms of the Gnu Public License
**    are limited to the Unix platform. Any distribution or compilation of 
**    the source code against libraries licensed other than gpl requires 
**    the written permission of the authors.
**
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR 
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY 
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**
**
** CrossVC License for Unix platforms:
**
** This program is free software; you can redistribute it and/or modify 
** it under the terms of the GNU General Public License as published by 
** the Free Software Foundation, version 2 of the License.
** This program is distributed in 
** the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
** even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
** PARTICULAR PURPOSE.
**
** See the GNU General Public License version 2 for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation,
** Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
*****************************************************************************/

#include "config.h"

//----------------------------------------------------------------------------

#include <qapplication.h>
#include <qtextcodec.h>
#include <qtranslator.h>
#include <qregexp.h>

#include <iostream>
#include <stdio.h>
#include <cstdlib>

//----------------------------------------------------------------------------

#include "globals.h"
#include "lincvs.h"
#include "LinCVSLog.h"
#include "wrapper.h"
#include "GuiEventBlocker.h"

//----------------------------------------------------------------------------

#ifndef Q_WS_WIN
#define STARTHELPCONSOLE
#define FINISHHELPCONSOLE
#else
#include "win-funcs.h"
#endif

//#define DEBUG

//----------------------------------------------------------------------------
using std::abort;
using std::getenv;

ApplicationWindow  *LinMainW;

bool bDebug = false;

//----------------------------------------------------------------------------

#ifdef DEBUG

#include <qeventloop.h>

class LinCVSEventLoop : public QEventLoop {

public:
  LinCVSEventLoop(QObject * parent = 0, const char * name = 0) : QEventLoop(parent, name) {}

  bool processEvents( ProcessEventsFlags flags) {
    qDebug("processEvents(%i)",flags);
    return QEventLoop::processEvents(flags | blockFlag);
  }

  static void setGUIBlocking(bool block) {
    if (block) {
      blockFlag = ExcludeUserInput;
    } else {
      blockFlag = AllEvents;
    }
  }

private:
  static ProcessEventsFlags blockFlag;

};
QEventLoop::ProcessEventsFlags LinCVSEventLoop::blockFlag = 0;
#endif

//----------------------------------------------------------------------------

void messageHandler( QtMsgType type, const char *msg ) {
  switch ( type )
  {
  case QtDebugMsg:
     if (bDebug) fprintf( stderr, "Debug: %s\n", msg );
     if (Debug::g_pLog) Debug::g_pLog->log(Debug::LL_THE_OLD_MAN_AND_THE_SEA,QString("Debug: ")+msg);
     break;
  case QtWarningMsg:
     if (bDebug && strncmp(msg,"QDate",5)) fprintf( stderr, "Warning: %s\n", msg );
     if (Debug::g_pLog) {
	if (Debug::g_logLevel <= Debug::LL_INFO && strncmp(msg,"QDate",5)) {
           Debug::g_pLog->log(Debug::LL_THE_OLD_MAN_AND_THE_SEA,QString("Warning: ")+msg);
	} else {
           Debug::g_pLog->log(Debug::LL_DEBUG,QString("Warning: ")+msg);
	}
     }
     break;
  case QtFatalMsg:
     fprintf( stderr, "Fatal: %s\n", msg );
     if (Debug::g_pLog) Debug::g_pLog->log(Debug::LL_THE_OLD_MAN_AND_THE_SEA,QString("Fatal: ")+msg);
     abort();// deliberately core dump
  }
}

//----------------------------------------------------------------------------

int showHelp(QString message) {

   STARTHELPCONSOLE;

   std::cout << message.latin1();
   std::cout << "\nUsage: crossvc [options [arguments]] [dir]" << std::endl;
   std::cout << "where options are:" << std::endl;
   std::cout << "\t-d --debug               write debug info to console" << std::endl;
   std::cout << "\t-i --iconic              start iconized" << std::endl;
   std::cout << "\t-s --small-icons         use small icons (useful on some window managers)" << std::endl;
   std::cout << "\t-o --on-the-fly          force on-the-fly dir scanning mode" << std::endl;
   std::cout << "\t-l --lang language-code  use passed language instead of language of environment" << std::endl;
#ifdef Q_WS_X11
   std::cout << "\t-r --rcpath              add rcpath to the search path for config files" << std::endl;
#endif
   std::cout << "\t-v --version             show version" << std::endl;
   std::cout << "\t-h --help                show this text" << std::endl;
   std::cout << "\n\tIf dir is specified,\n\tCrossVC will start with only this dir in workbench" << std::endl << std::endl;
     
   FINISHHELPCONSOLE;
   return 0;
}

//----------------------------------------------------------------------------

int main( int argc, char ** argv ) 
{
   QString message = "";
   QString arg;
   int i;
   for (i = 1; i < argc; i++) {//check for options that require an answer before connection to display
      arg = argv[i];
      if ((arg == "-v") || (arg == "--version")) {
         STARTHELPCONSOLE;
         std::cout << "CrossVC version " << LC_VERSION << "\n";
         FINISHHELPCONSOLE;
         return 0;
      } else if ((arg == "-h") || (arg == "--help")) {
         showHelp(message);
         return 0;
      }
   }

   initGlobals();

#ifdef DEBUG
   new LinCVSEventLoop();
#endif
   QApplication a(argc,argv);
   a.installEventFilter(new GuiEventBlocker());

   bool bIconic = false;
   bUseSmallIcons = false;
   QString startUpDir = QString::null;
   QString lang = QString::null;
#ifdef Q_WS_X11
   Misc::g_rcPath = "";
#endif

   for (i = 1; i < argc; i++) {    // a.argc() == argc
      arg = argv[i];                 // a.argv()[i] == argv[i]
      if (arg == "-qws") { continue; }               //qt-embedded
      else if ((arg == "-d") || (arg == "--debug")) { bDebug = true; continue;}
      else if ((arg == "-i") || (arg == "--iconic")) { bIconic = true; continue;}
      else if ((arg == "-s") || (arg == "--small-icons")) { bUseSmallIcons = true; continue;}
      else if ((arg == "-o") || (arg == "--on-the-fly")) { bOVERRIDEONTHEFLYSCANNING = true; continue;}
      else if ( !arg.startsWith("-")) {
         QFileInfo fileInfo(arg);
         if (fileInfo.isDir()) {
            bStartedInDir = true;
            startUpDir = arg.replace (QRegExp ("/+$"), "");
         } else {
            message = "\nNot a directory: " + arg + "\n";
            showHelp(message);
            return 0;
         }
      }
      else if ((arg == "-l") || (arg == "--lang")) {
         i++;
         bool bNoLang = false;
         if (i >= argc) bNoLang = true;
         else {
            arg = argv[i];                 // a.argv()[i] == argv[i]
            if (arg.startsWith("-")) bNoLang = true;
            else lang = arg;
         }
         if (bNoLang) {
            message = "\nNo language code specified\n";
            showHelp(message);
            return 0;
         }
      }
#ifdef Q_WS_X11
      else if ((arg == "-r") || (arg == "--rcpath")) {
         i++;
         bool bNoPath = false;
         if (i >= argc) bNoPath = true;
         else {
            arg = argv[i];                 // a.argv()[i] == argv[i]
            if (arg.startsWith("-")) bNoPath = true;
            else Misc::g_rcPath = arg;
         }
         if (bNoPath) {
            message = "\nNo additional search path for config files specified\n";
            showHelp(message);
            return 0;
         }
}
#endif
#ifndef Q_WS_MAC     
      else {
         message = "\nUnknown option: " + arg;
         showHelp(message);
         return 0;
      }
#endif       
   }

   qInstallMsgHandler( messageHandler );
   
   APPDIR = LW::appDir(a.argv()[0]);
   if (bDebug) qDebug("AppDir: " + APPDIR);
   

   //install translator
   if (lang.isEmpty()) lang = QString(QTextCodec::locale());

   //Some dist. add sth. like '.UTF-8' to '$LANG' -> remove the appendix
   int pos = lang.find('.');
   if (pos > -1) lang.truncate(pos);
   if (bDebug) qDebug("LANG: " + lang);

   QString messagesDir = APPDIR + "/" + LC_MESSAGES_DIR;
   bool qt_ts_found = false;
   QTranslator translator( 0 );
   QTranslator qtTranslator( 0 );
   translator.load( lang, messagesDir );
   
#ifdef Q_WS_WIN
   if (qtTranslator.load( "qt_" + lang, messagesDir )) {
      qt_ts_found = true;
      if (bDebug) qDebug("qt_*.qm found (in QTDIR)");
   } else {
      if (qtTranslator.load( "qt_" + lang, QString(getenv(("QTDIR"))) + "/translations/" )) {
         qt_ts_found = true;
         if (bDebug) qDebug("qt_*.qm found (in LC_MESSAGES_DIR)");
      }
   }
#else
   if (qtTranslator.load( "qt_" + lang, QString(getenv(("QTDIR"))) + "/translations/" )) {
      qt_ts_found = true;
      if (bDebug) qDebug("qt_*.qm found (in QTDIR)");
   } else {
      if (qtTranslator.load( "qt_" + lang, messagesDir )) {
         qt_ts_found = true;
         if (bDebug) qDebug("qt_*.qm found (in LC_MESSAGES_DIR)");
      }
   }
#endif // Q_WS_WIN
   a.installTranslator( &translator );
   if (qt_ts_found) a.installTranslator( &qtTranslator );
   
   LinMainW = new ApplicationWindow(startUpDir);

   I18n::init();


   QString caption = QObject::tr("%1 for %2 - Version %3");

#ifdef Q_WS_WIN
   QString os = "Windows";
#else
#ifdef Q_WS_MAC
   QString os = "MAC OS X";
#else
   QString os = "UNIX";
#endif
#endif

   LinMainW->setCaption(caption.arg(LC_APPNAME).arg(os).arg(LC_VERSION));


   QPoint bottomRightDesktop = QApplication::desktop()->geometry().bottomRight();
   QRect  mainWidgetGeom( GEOM_X, GEOM_Y, GEOM_WIDTH, GEOM_HEIGHT);
   QPoint topLeftMainWidget = mainWidgetGeom.topLeft();
   if( (topLeftMainWidget.x() > bottomRightDesktop.x()) ||
       (topLeftMainWidget.y() > bottomRightDesktop.y()))
      mainWidgetGeom.moveTopRight( QPoint(0,0));
   LinMainW->setGeometry( mainWidgetGeom);

   if (bIconic) LinMainW->showMinimized();
   else LinMainW->show();

   a.setMainWidget(LinMainW);

   a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );
   int res = a.exec();

   I18n::destroy();

   return res;
}

