/*
   Libre Media Server - A Media Server Sotfware for stage and performing
   Copyright (C) 2012-2013  Santiago Noreña libremediaserver@gmail.com

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <QApplication>
#include "libremediaserver.h"

// Handler for pipe the stderr to a log file

bool initMessageHandler = 0;
QFile outFile;

void MessageHandler(QtMsgType type, const char *msg)
{
    QString txt;
    switch (type) {
    case QtDebugMsg:
        txt = QString("Debug: %1").arg(msg);
        break;
    case QtWarningMsg:
        txt = QString("Warning: %1").arg(msg);
    break;
    case QtCriticalMsg:
        txt = QString("Critical: %1").arg(msg);
    break;
    case QtFatalMsg:
        txt = QString("Fatal: %1").arg(msg);
        abort();
    }
    if (!initMessageHandler)
    {
        QDir dir;
        if (!dir.exists("log"))
        {
            if (!dir.mkdir("log"))
            {
                qDebug()<<"MessageHandler: Can not create log folder";
                return;
            }
        }
        QString filename;
        QDate date = QDate::currentDate();
        QTime time = QTime::currentTime();
        filename.append("./log/log_");
        filename.append(date.toString("ddMMyy-"));
        filename.append(time.toString("hhmmss.txt"));
        outFile.setFileName(filename);
        if (!outFile.open(QIODevice::WriteOnly | QIODevice::Append))
        {
            qDebug()<<"main/MessageHandler/Qfile::open: can not open log file";
            return;
        }
        initMessageHandler = 1;
    }
    QTextStream ts(&outFile);
    ts << txt << endl;
}

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);
  qInstallMsgHandler(MessageHandler);
  libreMediaServer libreMediaServer;
  libreMediaServer.show();
  return app.exec();
}


