//
// 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 <list>
#include <utility>

#include <iostream>

#include <QString>

/** 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.toStdString();
}

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

/** Converts the handed string to html.
  *
  * It replaces linebreaks by &lt;br&gt; and &lt;/&gt;
  * by their HTML encoding.
  *
  * @param string the string to be converted
  * @param preserveWs if set to true, spaces will be replace by &amp;nbsp;
  *
  * This function should be static at one point.
  */
inline QString toHtml(const QString& input, bool preserveWs = false)
{
    std::list< std::pair<QChar, QString> > replacements;
    replacements.push_back(std::make_pair(QChar('<'),QString("&lt;")));
    replacements.push_back(std::make_pair(QChar('>'),QString("&gt;")));
    // 		_repl.push_back(make_pair(QChar('\n'),QString("<br>")));
    QString result = input;
    if (preserveWs)
        replacements.push_back(std::make_pair(QChar('>'),QString("&nbsp;")));
    for (auto it = replacements.begin(); it != replacements.end(); ++it)
        result.replace(it->first, it->second);
    return result;
}

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
