#include "log2ui.h"
#include <QtCore/QMetaType>
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
#include <QtCore/QCoreApplication>
#include <QtCore/QTime>
#include <QtWidgets/QApplication>
#include <QtWidgets/QAbstractButton>
#include <QtWidgets/QListWidget>
#include "api/errorcode.h"
#include <stdio.h>

bool logFilter(const char* file) {
    if (NULL == file) {
        return false;
    }
	static std::string logfiles[] = { "avd_howtodo.cpp", "use_engine.cpp", "com_room.cpp", "com_video.cpp", "com_audio.cpp", "dlg_videobitrates.cpp", "use_video.cpp", };
	int len = sizeof(logfiles) / sizeof(logfiles[0]);
	for (int i = 0; i < len; ++i) {
		const char *p = strstr(file, logfiles[i].c_str());
		if (NULL != p) {
		//if (0 == strcmp(logfiles[i].c_str(), file)) {
			return true;
		}
	}
	return false;
}
///
void static msgHandlerFunction(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
	if (!logFilter(context.file)) {
		return;
	}
	QMetaObject::invokeMethod(MsgHandlerWapper::instance(), "message"
		, Q_ARG(QtMsgType, type)
		, Q_ARG(QString, msg));
}

MsgHandlerWapper * MsgHandlerWapper::m_instance = 0;

MsgHandlerWapper * MsgHandlerWapper::instance()
{
	static QMutex mutex;
	if (!m_instance) {
		QMutexLocker locker(&mutex);
		if (!m_instance)
			m_instance = new MsgHandlerWapper;
	}

	return m_instance;
}

///
MsgHandlerWapper::MsgHandlerWapper()
:QObject(qApp)
{
	qRegisterMetaType<QtMsgType>("QtMsgType");
	qInstallMessageHandler(msgHandlerFunction);
}

///
#include <QTextCodec>  

QTextCodec *g_textcodec = QTextCodec::codecForName("utf-8");
void initTextCodec() {
	QTextCodec::setCodecForLocale(g_textcodec);
}

QString OutputWithRet(Result ret) {
	if (RT_SUCCEEDED(ret)) {
		return Utf8Str("成功");
	}
    else {
        QString msg = "failed, ret=%1";
        return msg.arg(ret);
		QString strTemp(Utf8Str("失败: ret="));
		strTemp.append(ret);
        return strTemp.toUtf8().data();
	}
}


///
int GetRandomNumber()
{
	qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
	return qrand() % 997;
}
std::string GetRandomNumberWithPrefix(const std::string& pre) {
	int num = GetRandomNumber();
	char szBuff[64] = { 0 };
	sprintf(szBuff, "%s%d", pre.c_str(), num);
	return std::string(szBuff);
}

void ButtonChecked(QAbstractButton* btn, bool checked, const QString& text) {
	btn->setChecked(checked);
	btn->setText(text);
}

void QListWidgetAddItem(QListWidget* lst, const char* name, const char* id) {
	QListWidgetItem* item = new QListWidgetItem;
	item->setData(Qt::DisplayRole, name);
	item->setData(Qt::UserRole, id);
	lst->addItem(item);
}

QString GetLogFile() {
    QString currentDir = QApplication::applicationDirPath();
    int pos = currentDir.lastIndexOf(RT_OS_SEPARATE);
    if (pos != currentDir.length() - 1)
    { currentDir.append(RT_OS_SEPARATE); }
    currentDir.append(Utf8Str("avd_howtodo_") + QString::number(QApplication::applicationPid(), 10));
    return currentDir;
}
