/*****************************************************************************
 * Copyright (C) 2004-2009 Christoph Thielecke <crissi99@gmx.de>             *
 *                                                                           *
 * 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 2 of the License, or         *
 * (at your option) any later version.                                       *
 *                                                                           *
 * This package 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 package; if not, write to the Free Software               *
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA *
 *****************************************************************************/

#include "logviewerdialog.h"

#include <QtCore/QTextStream>
#include <QtCore/QString>
#include <QtCore/QFile>
#include <QtGui/QColor>
#include <QtGui/QTextCharFormat>
#include <QtGui/QTextCursor>
#include <QtGui/QTextDocument>
#include <QtGui/QTextFormat>
#include <QtGui/QCursor>
#include <QtGui/QPixmap>

#include <qlistview.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klineedit.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <knuminput.h>
#include <kprogressdialog.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <ktextbrowser.h>
#include <kvpnc.h>

LogViewerDialog::LogViewerDialog(QWidget *parent, QApplication *app, KVpncConfig *GlobalConfig, const QString& caption, int count) : KDialog(parent)
{
    Q_UNUSED(caption);

    QWidget *page = new QWidget(this);
    setupUi(page);
    setMainWidget(page);

    // setMinimumSize(sizeHint());
    setMinimumSize(750, 500);
    LineCountIntSpinBox->setValue(count);

    this->GlobalConfig = GlobalConfig;
    this->app = app;

    //  QPixmap info_icon = KIconLoader::global()->loadIcon( "dialog-ok", KIconLoader::NoGroup, 16 );
    //  QPixmap debug_icon = KIconLoader::global()->loadIcon( "dialog-cancel", KIconLoader::NoGroup, 16 );
    //  QPixmap error_icon = KIconLoader::global()->loadIcon( "dialog-ok", KIconLoader::NoGroup, 16 );
    //  QPixmap debug_icon = KIconLoader::global()->loadIcon( "dialog-cancel", KIconLoader::NoGroup, 16 );

    // InfoListView->setSorting(1);

    connect(LineCountApplyPushButton, SIGNAL(clicked()), this, SLOT(updateLineCountClicked()));
    connect(FindPushButton, SIGNAL(clicked()), this, SLOT(findLogEntryClicked()));

    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    parseLog();
    QApplication::restoreOverrideCursor();

    showLogPart(count* -1, count);
}
LogViewerDialog::~LogViewerDialog()
{}

void LogViewerDialog::accept()
{
    QDialog::accept();
}


void LogViewerDialog::parseLog()
{

    KStandardDirs *dirs = KGlobal::dirs();
    QString logfileName = dirs->saveLocation("data");
    logfileName += "/kvpnc/kvpnc.log";
    QFile logfile;
    int linecount = 0;
    logfile.setFileName(logfileName);

    if (logfile.open(QIODevice::ReadOnly)) {
        char *tmpbuf = new char[500];
        int localcount = 0;
        while (logfile.readLine(tmpbuf, 500) > -1) {
            linecount++;
            localcount++;
            if (localcount == 50) {
                localcount = 0;
                app->processEvents();
            }
        }
        logfile.close();
        delete tmpbuf;
    }

    KProgressDialog *ProgressDlg = new KProgressDialog();
    ProgressDlg->setLabelText(i18n("Loading log..."));
// i18n("Load progress")

    ProgressDlg->progressBar()->setMinimum(0);
    ProgressDlg->progressBar()->setMaximum(linecount);
    ProgressDlg->show();
    ProgressDlg->resize(ProgressDlg->width() + 100, ProgressDlg->height());

    if (logfile.open(QIODevice::ReadOnly)) {
        QTextStream stream(&logfile);
        QString line;
        QString lines;
        QString prefix;
        QString postfix;
//   int type=0;
        int i = 0;
        int localcount = 0;
        while (!stream.atEnd()) {
            line = stream.readLine(); // line of text excluding '\n'
            LogList.append(line);
            i++;
            localcount++;
            ProgressDlg->progressBar()->setValue(i);
            if (localcount == 100) {
                localcount = 0;
                app->processEvents();
            }
        }
        logfile.close();
        LineCountIntSpinBox->setMaximum(i);
    }
    ProgressDlg->close();

}

void LogViewerDialog::updateLineCountClicked()
{
    int count = LineCountIntSpinBox->value();
    LogTextBrowser->clear();
    showLogPart(count* -1, count);
}

/**
 *
 * @param start
 * @param count
 */
void LogViewerDialog::showLogPart(int start, int count, bool parseLogType)
{
    int startval = 0;
    if (start < 0) {
        // startval entries from end

        if (int(LogList.count() + start - 1) < 0)
            startval = 0;
        else
            startval = LogList.count() - 1 + start;
        if (count + start > 0)
            count = LogList.count() - 1;

    } else if (start > 0) {



    }


//   QString msg = QString("start: ");
//   msg+=QString().setNum(startval);
//   msg+=QString(", count: ");
//   msg+=QString().setNum(count);
//   msg+=QString(", loglist.count: ");
//   msg+=QString().setNum(LogList.count());
//   KMessageBox::information(0,msg,"aaa");


    for (int index = startval;index <= startval + count;index++) {
        QString prefix = "";
        QString postfix = "";
        int type = KVpncEnum::info;
        QString line = LogList[index];
        if (!line.isEmpty()) {
            if (parseLogType) {
                if (line.indexOf(i18n("Info:"), 0, Qt::CaseInsensitive) > -1) {
                    type = KVpncEnum::info;
                } else if (line.indexOf(i18n("Debug:"), 0, Qt::CaseInsensitive) > -1) {
                    type = KVpncEnum::debug;
                }
                //    else
                //    if (line.indexOf(QString("remote"),0, Qt::CaseInsensitive) > -1 )
                //    {
                //     type = KVpncEnum::remote;
                //    }
                else
                    if (line.indexOf(i18n("Error:"), 0, Qt::CaseInsensitive) > -1) {
                        type = KVpncEnum::error;
                    }
                //    else
                //    if (line.indexOf(QString("success"),0, Qt::CaseInsensitive) > -1 )
                //    {
                //     type = KVpncEnum::success;
                //    }


                prefix += "<font color=\"";

                switch (type) {
                case KVpncEnum::info:
                    prefix += GlobalConfig->InfoLogColor.name();
                    prefix += "\">";
                    //      prefix+=i18n("info")+": ";
                    break;
                case KVpncEnum::remote:
                    prefix += GlobalConfig->RemoteLogColor.name();
                    prefix += "\">";
                    //      prefix+=i18n("remote")+": ";
                    break;
                case KVpncEnum::error:
                    prefix += GlobalConfig->ErrorLogColor.name();
                    prefix += "\">";
                    //      prefix+=i18n("error")+": ";
                    break;
                case KVpncEnum::success:
                    prefix += GlobalConfig->SuccessLogColor.name();
                    prefix += "\">";
                    //      prefix+=i18n("success")+": ";
                    break;
                case KVpncEnum::debug:
                    prefix += GlobalConfig->DebugLogColor.name();
                    prefix += "\">";
                    //      prefix+=i18n("debug")+": ";
                    break;
                }

                postfix += "</font>";
                LogTextBrowser->append(QString().setNum(index) + " " + prefix + line + postfix) ;
            } else {
                LogTextBrowser->append(QString().setNum(index) + " " + line) ;
            }
        }
    }
}

void LogViewerDialog::find(QString searchString)
{
    LogTextBrowser->find(searchString, QTextDocument::FindCaseSensitively);
}

void LogViewerDialog::findLogEntryClicked()
{
    find(SearchLineEdit->text());
}

#include "logviewerdialog.moc"
