/***************************************************************************
 *   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 <tdelocale.h>
#include <tdelistview.h>
#include <tqpixmap.h>
#include <tdeglobal.h>
#include <tqstring.h>
#include <tqcursor.h>
#include <kiconloader.h>
#include <kstandarddirs.h>
#include <ktextbrowser.h>
#include <knuminput.h>
#include <kpushbutton.h>
#include <klineedit.h>
#include <kprogress.h>
#include <iostream>
#include <kvpnc.h>
#include <tqfile.h>
#include <tqtextstream.h>
#include <tdemessagebox.h>

LogViewerDialog::LogViewerDialog(TQWidget *parent, TQApplication *app, KVpncConfig *GlobalConfig,const TQString& 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;

	// 	TQPixmap info_icon = TDEGlobal::iconLoader()->loadIcon( "button_ok", TDEIcon::NoGroup, 16 );
	// 	TQPixmap debug_icon = TDEGlobal::iconLoader()->loadIcon( "button_cancel", TDEIcon::NoGroup, 16 );
	// 	TQPixmap error_icon = TDEGlobal::iconLoader()->loadIcon( "button_ok", TDEIcon::NoGroup, 16 );
	// 	TQPixmap debug_icon = TDEGlobal::iconLoader()->loadIcon( "button_cancel", TDEIcon::NoGroup, 16 );

	//	InfoListView->setSorting(1);

	connect (main->LineCountApplyPushButton,TQ_SIGNAL(clicked()),this, TQ_SLOT(updateLineCountClicked()));
	connect (main->FindPushButton,TQ_SIGNAL(clicked()),this, TQ_SLOT(findLogEntryClicked()));

	TQApplication::setOverrideCursor( TQCursor(TQt::WaitCursor) );
	parseLog();
	TQApplication::restoreOverrideCursor();

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

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


void LogViewerDialog::parseLog()
{

	TDEStandardDirs *dirs = TDEGlobal::dirs();
	TQString logfileName = dirs->saveLocation( "data" );
	logfileName += "/kvpnc/kvpnc.log";
	TQFile 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 ))
	{
		TQTextStream stream( &logfile );
		TQString line;
		TQString lines;
		TQString prefix;
		TQString 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)
	{



	}


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

	for ( int index = startval;index <= startval+count;index++)
	{
		TQString prefix="";
		TQString postfix="";
		int type=KVpncConfig::info;
		TQString 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( TQString().setNum(index)+" "+prefix+line+postfix) ;
			}
			else
			{
				main->LogTextBrowser->append( TQString().setNum(index)+" "+line) ;
			}
		}
	}
}

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

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

#include "logviewerdialog.moc"
