/***************************************************************************
 *   Copyright (C) 2004 by 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 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, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "logviewerdialog.h"
#include <klocale.h>
#include <klistview.h>
#include <qpixmap.h>
#include <kglobal.h>
#include <qstring.h>
#include <qcursor.h>
#include <kiconloader.h>
#include <kstddirs.h>
#include <ktextbrowser.h>
#include <knuminput.h>
#include <kpushbutton.h>
#include <klineedit.h>
#include <kprogress.h>
#include <iostream>
#include <kvpnc.h>
#include <qfile.h>
#include <qtextstream.h>
#include <kmessagebox.h>

LogViewerDialog::LogViewerDialog(QWidget *parent, QApplication *app, KVpncConfig *GlobalConfig,const QString& caption, int count) : KDialogBase( parent, "Show_log", false, caption,
KDialogBase::Ok|KDialogBase::Cancel,KDialogBase::Ok, true )
{
	main = new LogViewerDialogBase (this);
	setMainWidget(main);
	//	main->setMinimumSize(main->sizeHint());
	main->setMinimumSize(750,500);
	main->LineCountIntSpinBox->setValue(count);

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

	// 	QPixmap info_icon = KGlobal::iconLoader()->loadIcon( "button_ok", KIcon::NoGroup, 16 );
	// 	QPixmap debug_icon = KGlobal::iconLoader()->loadIcon( "button_cancel", KIcon::NoGroup, 16 );
	// 	QPixmap error_icon = KGlobal::iconLoader()->loadIcon( "button_ok", KIcon::NoGroup, 16 );
	// 	QPixmap debug_icon = KGlobal::iconLoader()->loadIcon( "button_cancel", KIcon::NoGroup, 16 );

	//	InfoListView->setSorting(1);

	connect (main->LineCountApplyPushButton,SIGNAL(clicked()),this, SLOT(updateLineCountClicked()));
	connect (main->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;
	//std::cout << "file exists: " << logfile.exists() << std::endl;
	logfile.setName( logfileName );

	if (logfile.open(IO_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;
	}

// 	std::cout << "count: " << linecount << std::endl;

	KProgressDialog *ProgressDlg = new KProgressDialog (0, "loadprogress", i18n("Load progress"), i18n("Loading log..."), true);
	ProgressDlg->progressBar()->setTotalSteps(linecount);
	ProgressDlg->show();
	ProgressDlg->resize(ProgressDlg->width()+100,ProgressDlg->height());

	if (logfile.open(IO_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();
		main->LineCountIntSpinBox->setMaxValue(i);
	}
	ProgressDlg->close();

}

void LogViewerDialog::updateLineCountClicked()
{
	int count = main->LineCountIntSpinBox->value();
	main->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=KVpncConfig::info;
		QString line = LogList[index];
		if (!line.isEmpty())
		{
			if (parseLogType)
			{
				if (line.find(i18n("Info:"),0, FALSE) > -1 )
				{
					type = KVpncConfig::info;
				}
				else if (line.find(i18n("Debug:"),0, FALSE) > -1 )
				{
					type = KVpncConfig::debug;
				}
				// 			else
				// 			if (line.find("remote",0, FALSE) > -1 )
				// 			{
				// 				type = KVpncConfig::remote;
				// 			}
				else
					if (line.find(i18n("Error:"),0, FALSE) > -1 )
					{
						type = KVpncConfig::error;
					}
				// 			else
				// 			if (line.find("success",0, FALSE) > -1 )
				// 			{
				// 				type = KVpncConfig::success;
				// 			}


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

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

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

void LogViewerDialog::find(QString what)
{
	bool casesense=false;
	bool whooleword=false;
	main->LogTextBrowser->find(what,casesense,whooleword);
}

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

