/***************************************************************************
 *   Copyright (C) 2005 by Nicolas Ternisien                               *
 *   nicolas.ternisien@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 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.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.             *
 ***************************************************************************/

//TQt includes
#include <tqpushbutton.h>
#include <tqradiobutton.h>
#include <tqcheckbox.h>

//KDE includes
#include <tdelocale.h>
#include <kurlrequester.h>
#include <kcombobox.h>
#include <klineedit.h>
#include <kdebug.h>
#include <kprocess.h>
#include <tdemessagebox.h>

//Project includes
#include "logLevel.h"
#include "globals.h"

#include "loggerDialog.h"

LoggerDialog::LoggerDialog(TQWidget *parent, const char *name) :
	LoggerDialogBase(parent, name) {
		
	connect(buttonOK, TQ_SIGNAL(clicked()), this, TQ_SLOT(sendMessage()));
	
	connect(tagActivation, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(tagActivationChanged(bool)));
	connect(fileActivation, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(fileActivationChanged(bool)));
	connect(messageActivation, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(messageActivationChanged(bool)));
	
	
	connect(file, TQ_SIGNAL(textChanged(const TQString&)), this, TQ_SLOT(textChanged(const TQString&)));
	connect(message, TQ_SIGNAL(textChanged(const TQString&)), this, TQ_SLOT(textChanged(const TQString&)));
	connect(tag, TQ_SIGNAL(textChanged(const TQString&)), this, TQ_SLOT(textChanged(const TQString&)));

	buildMaps();
	
	//Fill the priority ComboBox
	TQValueList<TQString> prioKeys(priorities.keys());
	
	TQValueList<TQString>::Iterator itPriority;
	for (itPriority=prioKeys.begin(); itPriority!=prioKeys.end(); ++itPriority) {
		priority->insertItem(priorityIcons[*itPriority], *itPriority);
	}

	
	//Select the right priority
	for (int i=0; i<priority->count(); ++i) {
		if (priority->text(i)==Globals::noticeLogLevel->name) {
			priority->setCurrentItem(i);
			break;
		}	
	}

	//Fill the priority ComboBox
	TQValueList<TQString> keys(facilities.keys());
	
	TQValueList<TQString>::Iterator itFacility;
	for (itFacility=keys.begin(); itFacility!=keys.end(); ++itFacility) {
		facility->insertItem(*itFacility);
	}

	//Select the right facility
	for (int i=0; i<facility->count(); ++i) {
		if (facility->text(i)==i18n("User")) {
			facility->setCurrentItem(i);
			break;
		}
	}

}

void LoggerDialog::buildMaps() {

	//Fill the facility map
	facilities[i18n("Authentication")]="auth";
	facilities[i18n("Private Authentication")]="authpriv";
	facilities[i18n("Cron")]="cron";
	facilities[i18n("Daemon")]="daemon";
	facilities[i18n("FTP")]="ftp";
	facilities[i18n("Kernel")]="kern";
	facilities[i18n("LPR")]="lpr";
	facilities[i18n("Mail")]="mail";
	facilities[i18n("News")]="news";
	facilities[i18n("Syslog")]="syslog";
	facilities[i18n("User")]="user";
	facilities[i18n("UUCP")]="uucp";
	
	facilities[i18n("Local 0")]="local0";
	facilities[i18n("Local 1")]="local1";
	facilities[i18n("Local 2")]="local2";
	facilities[i18n("Local 3")]="local3";
	facilities[i18n("Local 4")]="local4";
	facilities[i18n("Local 5")]="local5";
	facilities[i18n("Local 6")]="local6";
	facilities[i18n("Local 7")]="local7";

	//Fill the priority map
	priorities[Globals::debugLogLevel->name]="debug";
	priorities[Globals::informationLogLevel->name]="info";
	priorities[Globals::noticeLogLevel->name]="notice";
	priorities[Globals::warningLogLevel->name]="warning";
	priorities[Globals::errorLogLevel->name]="err";
	priorities[Globals::criticalLogLevel->name]="crit";
	priorities[Globals::alertLogLevel->name]="alert";
	priorities[Globals::emergencyLogLevel->name]="emerg";
	
	//Fill the priority icon map
	priorityIcons[Globals::debugLogLevel->name]=Globals::debugLogLevel->pixmap;
	priorityIcons[Globals::informationLogLevel->name]=Globals::informationLogLevel->pixmap;
	priorityIcons[Globals::noticeLogLevel->name]=Globals::noticeLogLevel->pixmap;
	priorityIcons[Globals::warningLogLevel->name]=Globals::warningLogLevel->pixmap;
	priorityIcons[Globals::errorLogLevel->name]=Globals::errorLogLevel->pixmap;
	priorityIcons[Globals::criticalLogLevel->name]=Globals::criticalLogLevel->pixmap;
	priorityIcons[Globals::alertLogLevel->name]=Globals::alertLogLevel->pixmap;
	priorityIcons[Globals::emergencyLogLevel->name]=Globals::emergencyLogLevel->pixmap;

}

void LoggerDialog::textChanged(const TQString& /*text*/) {
	if (fileActivation->isChecked() && file->url().isEmpty()) {
		buttonOK->setEnabled(false);
		return;
	}

	if (tagActivation->isChecked() && tag->text().isEmpty()) {
		buttonOK->setEnabled(false);
		return;
	}
	
	if (messageActivation->isChecked() && message->text().isEmpty()) {
		buttonOK->setEnabled(false);
		return;
	}

	buttonOK->setEnabled(true);

}

void LoggerDialog::tagActivationChanged(bool activation) {
	tag->setEnabled(activation);
	
	textChanged("");
}

void LoggerDialog::fileActivationChanged(bool activation) {
	file->setEnabled(activation);
	
	textChanged("");
}

void LoggerDialog::messageActivationChanged(bool activation) {
	message->setEnabled(activation);
	
	textChanged("");
}


void LoggerDialog::sendMessage() {
	
	TDEProcess process;
	
	//process.setUseShell(true);
	process << "logger";
	
	if (useProcessIdentifier->isChecked()) {
		process << "-i";
	}
	
	if (tagActivation->isChecked()) {
		process << "-t";
		
		process << tag->text();
	}

	TQString prioritySelected=priority->currentText();
	
	if (prioritySelected!=Globals::noneLogLevel->name) {
		process << "-p";
		
		TQString p(facilities[facility->currentText()]);
		p+=".";
		p+=priorities[priority->currentText()];
		
		process << p;
	}

	//If we read the content of a file
	if (fileActivation->isChecked()) {
		process << "-f";
		
		process << file->url();
	}
	//Else, the user types the content of its message
	else {
		//Remove bad "\n" characters
		TQString msg=message->text().replace("\n", " ");
		
		process << msg;
	}

	bool launch=process.start( TDEProcess::Block, TDEProcess::Stdout );
	
	//If the launching of the command failed
	if (launch==false) {
		KMessageBox::error(this, i18n("Unable to find the 'logger' command on your system. Please type 'logger' in Konsole to be sure that this command does not exist."), i18n("Command not found"), KMessageBox::Error);
		return;
	}
	
	if (process.normalExit()==false) {
		KMessageBox::error(this, i18n("The 'logger' command has not been properly exited."), i18n("Execution problem"), KMessageBox::Error);
		return;
	}

	int returnCode=process.exitStatus();
	//No such file or directory
	if (returnCode==1) {
		KMessageBox::error(this, i18n("This file does not exist. Please choose a right file."), i18n("File not valid"), KMessageBox::Error);
		return;
	}

	//Hide the Logger Dialog
	hide();
}


#include "loggerDialog.moc"
