/****************************************************************************
** Main file
**
**   Created : Wed Jun 25 07:53:05 2008
**        by : Varol Okan
** Copyright : (c) Varol Okan
**   License : GPL v 2.0
**
** This is the main file.
**
****************************************************************************/

#include <unistd.h>

#include <QApplication>
#include <QtCore>

#include "utils.h"
#include "shared.h"
#include "server.h"
#include "parser.h"
#include "logger.h"

int main ( int argc, char *argv[] )
{
  QApplication app ( argc, argv );
  Render::Logger logger;
  // The parser class handles user input.
  // We can exit here if QRender is
  // not executed as deamon ( Client-Server )
  Render::Parser parser;
  if ( parser.parseCommandLine ( argc, argv ) )
    return 0;

  // First we check if the work can be done without starting a server
  // E.g. writing the regional code to the final DVD.
  if ( parser.getRegionalZone ( ) != -1 )  {
    Utils theUtils;
    theUtils.writeZoneCode ( (unsigned char)parser.getRegionalZone ( ), parser.getPath ( ) );
    return 0;
  }

  pid_t iPid = getpid ( );

  if ( ! parser.isTTY ( ) )
    daemon ( 1, 1 );

  // At this point we start the server thread and listen to the set port.
  Render::Server server;
  server.setLogInfo ( parser.getLogLevel ( ), parser.getLogfileName ( ) );
  logger.setLogInfo ( parser.getLogLevel ( ), parser.getLogfileName ( ) );

  if ( ! server.listen ( QHostAddress::Any, parser.getServerPort ( ) ) )  {
    // QRender is most likely alreadyt running in the background. So this is not an error per-se
    // but rather an expected exception.
    logger.log ( Render::Logger::logError, "ERROR: Can not bind to port 5066\n%s\n", (const char *)server.errorString ( ).toAscii ( ) );
  }
  else  {
    if ( ! parser.isTTY ( ) )
      logger.log ( Render::Logger::logInformation, "\nStarting QRender[%d] in deamon mode, Listening to port : %d\n\n", (int)iPid+1, parser.getServerPort ( ) );
    else
      logger.log ( Render::Logger::logInformation, "\nStarting QRender[%d] in the foreground, Listening to port : %d\n\n", (int)iPid+1, parser.getServerPort ( ) );
    return app.exec ( );
  }

  return -1;
}

