//
// C++ Implementation: main
//
// Description: 
//
//
// Author: Benjamin Mesing <bensmail@gmx.net>, (C) 2004
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include <string>
#include <iostream>

#include <QApplication>
#include <QDir>
#include <QLocale>
#include <QMessageBox>
#include <QTranslator>

#include <translationmanager.h>

#include "packagesearchimpl.h"

#include "helpers.h"

#include "globals.h"


using namespace std;

#include <stdio.h>
#include <stdlib.h>

void releaseMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
	switch ( type ) {
			case QtDebugMsg:
				// do nothing
				break;
			case QtWarningMsg:
				// do noting either
				break;
			case QtCriticalMsg:
			case QtFatalMsg:
                fprintf( stderr, "%s\n", msg.toStdString().c_str() );
				abort();                    // deliberately core dump
	}
}

void debugMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString category(context.category);
    switch ( type ) {
			case QtDebugMsg:
                // Some QT Debug noise (QT 5.9.1/6.x)
                if (msg.contains("XI2") || msg.contains("XCB_") || msg.contains("QGestureManager:Recognizer"))
                    return;
                // don't log qt-debug messages by default
                if (category.startsWith("qt"))
                    return;
                cout << "[Debug] " << context.category << " - " << msg << endl;
				break;
            case QtInfoMsg:
                cerr << "[Info] " << msg << endl;
                break;
            case QtWarningMsg:
                cerr << "[Warning] " << msg << endl;
				break;
			case QtCriticalMsg:
			case QtFatalMsg:
                cerr << msg << endl;
				abort();                    // deliberately core dump
	}
}

int main(int argc, char* argv[])
{
	QString usage(QApplication::translate("MainProgram", "Usage: packagesearch [options]\n"
		"\t-h, --help     prints this message\n"
		"\t-v, --version  prints the version information\n"
		"If started without options the UI is launched\n"));
    #ifdef __DEBUG
    qInstallMessageHandler( debugMessageOutput );
    #else
    qInstallMessageHandler( releaseMessageOutput );
    #endif

    QApplication a(argc, argv);

    TranslationManager::loadTranslation("packagesearch");

	if (argc > 1)
	{
		for (int i=1; i < argc; ++i)
		{
			QString arg(argv[i]);
			if (arg == "--version" || arg == "-v")
			{
				cout << toString(NPackageSearch::VERSION) << endl;
				return 0;
			}
			if (arg == "--help" || arg == "-h")
			{
				cout << usage;
				return 0;
			}
			cerr << a.translate("MainProgram", "Unknown option ") << argv[i] << endl;
			cerr << usage << endl; 
			return 1;
		}
	}
	PackageSearchImpl search(0, "MainWindow");
	search.setWindowTitle(a.translate("MainProgram", "Debian Package Search - Version ") + NPackageSearch::VERSION);
	search.show();
	search.initialize();
	return a.exec();
}

