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

#ifndef __HELPERS_H_2004_06_23
#define __HELPERS_H_2004_06_23

#include <string>
#include <cctype>	// for tolower
#include <algorithm>
#include <map>

#undef slots
#include <xapian.h>

#include <iostream>

#include <QString>

/** Gets the Document for the given package.
  *
  * @returns as first argument a boolean indicating if the package was found and the document
  * itself as second argument
  */
inline std::pair<bool, Xapian::Document> documentForPackage(const std::string& package, const Xapian::Database& xapian) 
{
	Xapian::Enquire enq(xapian);
	Xapian::Query queryPackage(std::string("XP")+package);
	enq.set_query(queryPackage);
	Xapian::MSet packageMatch = enq.get_mset(0, 1);
	if (packageMatch.size()==0)
	{
		return std::make_pair(false, Xapian::Document());
	}
	return std::make_pair(true, packageMatch.begin().get_document());
}

/** Converts the given string to a QString. This should mean no more overhead than
  * doing it manually. */
inline QString toQString(const std::string& str)
{
	return QString::fromStdString(str);
}

inline QString& toQString(QString& str)
{
	return str;
}

inline std::string toString(const QString& str)
{
//	return str.operator std::string();
    return std::string(str.toLatin1());
}

/** Avoid accidental conversions like toString(str) where str already is a std::string */
inline std::string& toString(std::string& str)
{
	return str;
}


inline int myToLower(int a)
{
	return tolower(a);
}

inline void qStrDebug(const QString& string)
{
    qDebug("%s", string.toLatin1().data());
}

inline void qStrWarning(const QString& string)
{
    qWarning("%s", string.toLatin1().data());
}

/** @brief Makes the given string lower case - modifies the handed string.
  * @returns a reference to the transformed string (which is the one handed). */
inline std::string& makeLower(std::string& trans)
{
	std::transform(trans.begin(), trans.end(), trans.begin(), myToLower);
	return trans;
}

/** Creates a string that differs from the given one only in being lower case. */
inline std::string toLower(const std::string& in)
{
	using namespace std;
	string result;
	std::transform(in.begin(), in.end(), back_inserter(result), myToLower);
	return result;
}

/** Operator for outputting QStrings. */
inline std::ostream& operator<< (std::ostream& out, const QString& str) 
{
    out << str.toLatin1().data();
	return out;
}

#endif	// __HELPERS_H_2004_06_23
