/*
 * Copyright (C) 2004 Robert Hogan <robert at roberthogan dot net>
 */

#include "schedule.h"
#include "klamav.h"
#include "datepicker.h"


#include "ktview.h"


#include <qlabel.h>
#include <kurlrequester.h>
#include <qlayout.h>
#include <qlistview.h>
//#include <qlistviewitem.h>
#include <kglobalsettings.h>
#include <kdialog.h>
#include <dcopclient.h>
#include <kstdguiitem.h>
#include <sys/stat.h>


Schedule::Schedule( QWidget* parent, QStringList filepattern, const char* name, bool modal, WFlags fl )
    : QDialog( parent, name, modal, fl )
{

	setCaption( i18n( "Schedule Scan" ) );

 	cthost = new CTHost();
 	const CTHost& cth(*cthost);

	// for each user
//  	CTCronIterator i = const_cast<CTHost&>(cth).cron.begin();
// 	CTCron* ctcron((CTCron*)*i);	


	_filepattern = filepattern;
	//bool isRTL = QApplication::reverseLayout();
	QVBoxLayout *vbox = new QVBoxLayout(this, KDialog::marginHint(),
			KDialog::spacingHint(), "vbox");
 
	QGroupBox *group = new QGroupBox("Schedule Scan of Selected Folders", this);
	vbox->addWidget(group);
	


	QGridLayout *layout = new QGridLayout( group, 6, 6, KDialog::spacingHint(),
			KDialog::spacingHint(), "layout");
	layout->addRowSpacing(0, group->fontMetrics().height());
	layout->setColStretch(0, 1);
	layout->setColStretch(1, 1);

	

	check_combo = new QComboBox(false, group);
   check_combo->insertItem( i18n("When I log in to KDE"));
   check_combo->insertItem( i18n("Every day at "));
   check_combo->insertItem( i18n("Every day at the current time"));
   check_combo->insertItem( i18n("Every week from now on at the current time"));
   check_combo->insertItem( i18n("Every week from now on at"));
   check_combo->insertItem( i18n("Every week from a specific date at"));
   check_combo->insertItem( i18n("Every month from now on at the current time"));
   check_combo->insertItem( i18n("Every month from now on at"));
   check_combo->insertItem( i18n("Every month from a specific date at"));
   check_combo->insertItem( i18n("Once only on a specific date at the current time"));
   check_combo->insertItem( i18n("Once only on a specific date at"));

 	layout->addWidget(check_combo,1,0);
 	connect( check_combo, SIGNAL(activated(int)),this,
 		SLOT(slotQueryDatePicker(int)) );


	hour = new HMSTimeWidget( group );
	hour->setWrapping(true);
	hour->setMaxValue(23);
	hour->setValidator(new KStrictIntValidator(0, 23, hour));
	layout->addWidget(hour, 1, 1);
	
	QLabel *dots1 = new QLabel(":", group);
	dots1->setMinimumWidth( 7 );
	dots1->setAlignment( QLabel::AlignCenter );
	layout->addWidget(dots1, 1, 2);
	
	minute = new HMSTimeWidget( group );
	minute->setWrapping(true);
	minute->setMinValue(0);
	minute->setMaxValue(59);
	minute->setValidator(new KStrictIntValidator(0, 59, minute));
	layout->addWidget(minute, 1, 3);




	QPushButton* add = new QPushButton ("Add", group);
	layout->addWidget(add,1,5);
	//add->setFixedSize(add->sizeHint());

 	connect( add, SIGNAL(clicked()),
 		SLOT(slotScheduleScan()) );

	QPushButton* del = new QPushButton ("Delete", group);
	layout->addWidget(del,1,6);
	//del->setFixedSize(del->sizeHint());

 	connect( del, SIGNAL(clicked()),
 		SLOT(slotDelete()) );


	//schedulebox = new QListView(group);
	schedulebox = new KTView(group);
	QFontMetrics rb_fm(schedulebox->fontMetrics());
	schedulebox->setMinimumSize(rb_fm.width("0")*55,
				rb_fm.lineSpacing()*15);
/*	//kdDebug() << ((schedulebox->width())/2) << endl;
	schedulebox->addColumn( "Paths to Scan",(group->width()));
        schedulebox->addColumn( "When to Scan",(group->width()));
	schedulebox->setResizeMode(QListView::AllColumns);
	schedulebox->setSelectionMode( QListView::Extended );
	schedulebox->setAllColumnsShowFocus(true);*/
	
	layout->addMultiCellWidget(schedulebox, 2, 4,0,6);

	QHBoxLayout *h5 = new QHBoxLayout( vbox, KDialog::spacingHint() );
	h5->addStretch( 1 );

	// OK
	KPushButton *pbOk = new KPushButton(KStdGuiItem::ok(), this, "pbOk");
	pbOk->setDefault(true);
	h5->addWidget( pbOk);
	
	// Cancel
// 	KPushButton *pbCancel = new KPushButton(KStdGuiItem::cancel(), this, "pbCancel");
// 	h5->addWidget( pbCancel);

	connect(pbOk, SIGNAL(clicked()), SLOT(slotOK()));
/*	connect(pbCancel, SIGNAL(clicked()), SLOT(slotCancel()));*/
	
	schedulebox->hideCommand();
}

Schedule::~Schedule()
{
	delete cthost;
}


void Schedule::slotQueryDatePicker(int index)
{

	if (check_combo->currentText().contains(i18n("specific date")) ){
		DatePicker *_calendar;	
		_calendar = new DatePicker(this, QDateTime::currentDateTime().date());
		int x = this->width() - (this->width()/2);
		int y = this->height() - (this->height()/2);
		_calendar->move(QPoint(x,y));
		_calendar->show();
		_calendar->setFocus();
		connect( _calendar, SIGNAL(signalSelectedDate(QDate)),this,
			SLOT(slotAddDateToCombo(QDate)) );

	}
}

void Schedule::slotAddDateToCombo(QDate newdate)
{

	//check_combo->insertItem
	_date = newdate;
	//kdDebug() << newdate.toString() << endl;
	QString newstring = check_combo->currentText().replace("a specific date",newdate.toString());
	check_combo->insertItem(newstring);
	check_combo->setCurrentItem(check_combo->count()-1);

	DCOPClient* client = KApplication::dcopClient();
	client->attach();
	client->registerAs(kapp->name());


	
}


void Schedule::slotScheduleScan()
{


/* 	cthost = new CTHost();*/
/* 	const CTHost& cth(*cthost);
// 
// 	// for each user
 	CTCronIterator i = const_cast<CTHost&>(cth).cron.begin();
 	CTCron* ctcron((CTCron*)*i);	*/
 
	//delete cttask;
	QString command = check_combo->currentText();

	
	
 	cttask = new CTTask ("", "", TRUE);

	cttask->user = "";

	if (command.contains(i18n("When I log in to KDE")) ){
		QString startupcommand = createStartupScript();
		cttask->comment = (const char *)i18n("KlamAV Scheduled Scan at KDE Login of %1").arg(_filepattern.join(" ")).local8Bit();
		cttask->command = (const char *)QString("%1").arg(startupcommand).local8Bit();
		cttask->enabled = FALSE;

	}else{
	
		cttask->comment = (const char *)i18n("KlamAV Scheduled Scan of %1").arg(_filepattern.join(" ")).local8Bit();
		cttask->command = (const char *)QString("%1 '%2'").arg(createScanScript()).arg(_filepattern.join("' '")).local8Bit();
		cttask->enabled = TRUE;
	}
	cttask->silent = FALSE;
	

	int curhour = (QTime::currentTime()).hour();
	unsigned int curmin = (QTime::currentTime()).minute();
	
	int shour = QString(hour->text()).toInt();
	unsigned int smin = QString(minute->text()).toInt();

	int sdatedayofweek = _date.dayOfWeek();
	int todaydayofweek = QDate::currentDate().dayOfWeek();


	if (command.contains(i18n("at the current time")) ){
		cttask->hour.set(curhour, TRUE);
		cttask->minute.set(curmin, TRUE);
	}else{
		cttask->hour.set(shour, TRUE);
		cttask->minute.set(smin, TRUE);
	}

	if (command.contains(i18n("Every week")) ){
		if (command.contains(i18n("from now on") ))
			cttask->dayOfWeek.set(todaydayofweek, TRUE);
		else
			cttask->dayOfWeek.set(sdatedayofweek, TRUE);
		for (int dm = 1; dm <= 31; dm++)
		{
			cttask->dayOfMonth.set(dm, true);
		}
		for (int mo = 1; mo <= 12; mo++)
		{
			cttask->month.set(mo, true);
		}

	}else if (command.contains(i18n("Every month")) ){
		if (command.contains(i18n("from now on") ))
			cttask->dayOfMonth.set(QDate::currentDate().day(), TRUE);
		else
			cttask->dayOfMonth.set(_date.day(), TRUE);
		for (int dw = 1; dw <= 7; dw++)
		{
		cttask->dayOfWeek.set(dw, true);
		}
		for (int mo = 1; mo <= 12; mo++)
		{
			cttask->month.set(mo, true);
		}
	}else if (command.contains(i18n("Every day")) ){
		for (int dw = 1; dw <= 7; dw++)
		{
		cttask->dayOfWeek.set(dw, true);
		}

		for (int dm = 1; dm <= 31; dm++)
		{
			cttask->dayOfMonth.set(dm, true);
		}
		for (int mo = 1; mo <= 12; mo++)
		{
			cttask->month.set(mo, true);
		}
	}else if (command.contains(i18n("Once only")) ){
		cttask->month.set(_date.month(), TRUE);
		cttask->dayOfMonth.set(_date.day(), TRUE);
	}else{
		cttask->month.set(1, TRUE);
		cttask->dayOfMonth.set(1, TRUE);
		cttask->dayOfWeek.set(1, true);
		cttask->hour.set(0, TRUE);
		cttask->minute.set(0, TRUE);

	}




	QString description = QString::fromLocal8Bit(cttask->describe().c_str()); 
	CTCron* ctcron(schedulebox->getCTCron());
	if (cttask->dirty())
		ctcron->task.push_back(cttask);
		//new KTListTask(this, ctcron, cttask); // Qt will clean up
	else
		delete cttask;


	schedulebox->refresh();
	cthost->apply();
	
	//QListViewItem* tm = new QListViewItem( schedulebox, _filepattern, description);

/*	if (cthost->isError())
	{
		KMessageBox::error(this, cthost->errorMessage());
	}
	//kdDebug() << "finished crontab" << endl;


	delete cthost;*/
}


void Schedule::slotDelete()
{

	//kdDebug() << schedulebox->currentItem()->text(1) << endl;
	QFile file(schedulebox->currentItem()->text(1).section(" ",0,0).stripWhiteSpace());
	file.remove();
	schedulebox->remove();
	cthost->apply();
}

void Schedule::slotOK()
{
	cthost->apply();
	close();
}

void Schedule::slotCancel()
{
	close();
}

QString Schedule::createScanScript()
{

	QString path = getenv("HOME");
	path += "/.klamav";
	QDir klamavdir(path);
	if (!klamavdir.exists() && !klamavdir.mkdir(path))
		return QString("Error");

	QTime now = QTime::currentTime();
	QDate today = QDate::currentDate();
	QString timestring = QString("%1%2")
		.arg(today.toString("ddMMyy"))
		.arg(now.toString("hhmmss"));

	QFile file( QString("%1/ScanWithKlamav_%2.sh").arg(path).arg(timestring ));

	if ( file.open( IO_WriteOnly ) ) {
		QTextStream ts( &file );
	
		QString kdedir = getenv("KDEDIR");
	
	
		ts << "#!/bin/bash" << "\n";
		ts << "HOSTNAME=`hostname`" << "\n";
		ts << "export HOSTNAME" << "\n";
		ts << QString("PATH=%1").arg(QString(getenv("PATH"))) << "\n";
		ts << "export PATH" << "\n";
		ts << "DCOPSERVER=`cat /home/$USER/.DCOPserver_$HOSTNAME_:0 | grep local`" << "\n";
		ts << "export DCOPSERVER" << "\n";
		ts << "DISPLAY=:0" << "\n";
		ts << "export DISPLAY" << "\n";
		ts << "# Execution starts here" << "\n";
		ts << "if [ \"$1\" = \"\" ]; then" << "\n";
		ts << "        exit 1" << "\n";
		ts << "fi" << "\n";
		ts << "until [ -z \"$1\" ]  # Until all parameters used up..." << "\n";
		ts << "do" << "\n";
		ts << "  if [ \"$URL\" = \"\" ]; then" << "\n";
		ts << "        URL=$1" << "\n";
		ts << "        SCANTHIS=$1" << "\n";
		ts << "  else" << "\n";
		ts << "        URL=$URL'*'$1" << "\n";
		ts << "        SCANTHIS=$SCANTHIS' '$1" << "\n";
		ts << "  fi" << "\n";
		ts << "  shift" << "\n";
		ts << "done" << "\n";
		ts << QString("if %1/bin/dcop `%2/bin/dcop|grep klamav|head -1` DCOPKlamscan scanURLs \"$URL\"; then").arg(kdedir).arg(kdedir) << "\n";
		ts << "        exit 0" << "\n";
		ts << "else" << "\n";
		ts << QString("        %1/bin/klamav --scanthis $SCANTHIS").arg(kdedir) << "\n";
		ts << "fi" << "\n";
	
		file.close();
		chmod((const char *)file.name(), S_IWUSR | S_IRUSR | S_IEXEC );
		return file.name();
	}else
		return QString("Error");

}

QString Schedule::createStartupScript()
{

	QString path = KGlobalSettings::autostartPath();
	QDir startupdir(path);
	if (!startupdir.exists())
		return QString("Error");

	QTime now = QTime::currentTime();
	QDate today = QDate::currentDate();
	QString timestring = QString("%1%2")
		.arg(today.toString("ddMMyy"))
		.arg(now.toString("hhmmss"));

	QFile file( QString("%1klamav_%2.desktop").arg(path).arg(timestring ));

	if ( file.open( IO_WriteOnly ) ) {
		QTextStream ts( &file );
	
		ts << "[Desktop Entry]" << "\n";
		ts << "Encoding=UTF-8" << "\n";
		ts << "Name=Klamav" << "\n";
		ts << QString("Exec=klamav %i %m -caption \"%c\" --scanthis '%1'").arg(_filepattern.join("' '")) << "\n";
		ts << "Icon=klamav" << "\n";
		ts << "Type=Application" << "\n";
		ts << "DocPath=klamav/klamav.html" << "\n";
		ts << "Comment=An Anti-Virus Manager" << "\n";
		ts << "Comment[cs]=Aplikace typu KPart" << "\n";
		ts << "Comment[da]=Et KDE KPart program" << "\n";
		ts << "Comment[de]=Ein KDE-Programm" << "\n";
		ts << "Comment[el]=Μια εφαρμογή KDE KPart" << "\n";
		ts << "Comment[eo]=KDEa Parto-aplikaĵo" << "\n";
		ts << "Comment[es]=Una aplicación KPart para KDE" << "\n";
		ts << "Comment[et]=KDE KPart rakendus" << "\n";
		ts << "Comment[fi]=KDE KPart sovellus" << "\n";
		ts << "Comment[fr]=Une Application KPart pour KDE" << "\n";
		ts << "Comment[he]=KDE לש KPart םושיי" << "\n";
		ts << "Comment[hu]=Egy KDE KPart tesztalkalmazás" << "\n";
		ts << "Comment[is]=KDE KPart forrit" << "\n";
		ts << "Comment[it]=Un'applicazione \"part\" di KDE" << "\n";
		ts << "Comment[ja]=KDE KPart アプリケーション" << "\n";
		ts << "Comment[ko]=KDE용 KPart 응용 프로그램" << "\n";
		ts << "Comment[lv]=KDE KPart Aplikācija" << "\n";
		ts << "Comment[nl]=een KDE KPart-applicatie" << "\n";
		ts << "Comment[no_NY]=Eit KDE KPart-program" << "\n";
		ts << "Comment[pt]=Uma aplicação KPart" << "\n";
		ts << "Comment[pt_BR]=Uma aplicação KPart do KDE" << "\n";
		ts << "Comment[ro]=O aplicaţie KPart pentru KDE" << "\n";
		ts << "Comment[ru]=Приложение KPart KDE" << "\n";
		ts << "Comment[sk]=KDE KPart aplikácia" << "\n";
		ts << "Comment[sl]=Program za KDE KPart" << "\n";
		ts << "Comment[sr]=KDE KPart aplikacija" << "\n";
		ts << "Comment[sv]=Ett KDE KPart-program" << "\n";
		ts << "Comment[tr]=KDE Kpart Uygulaması" << "\n";
		ts << "Comment[uk]=Програма KPart для KDE" << "\n";
		ts << "Comment[zh_CN.GB2312]=KDE KPart程序" << "\n";
		ts << "Terminal=0" << "\n";
	
		file.close();
		chmod((const char *)file.name(), S_IWUSR | S_IRUSR | S_IEXEC );
		return file.name();
	}else
		return QString("Error");

}



HMSTimeWidget::HMSTimeWidget(QWidget *parent, const char *name) :
	KIntSpinBox(parent, name)
{
}


QString HMSTimeWidget::mapValueToText(int value)
{
  QString s = QString::number(value);
  if( value < 10 ) {
    s = "0" + s;
  }
  return s;
}

QValidator::State KStrictIntValidator::validate( QString & input, int & d ) const
{
  if( input.isEmpty() )
    return Valid;

  State st = QIntValidator::validate( input, d );

  if( st == Intermediate )
    return Invalid;

  return st;
}

const CTHost& Schedule::getCTHost() const
{
  return *cthost;
}


#include "schedule.moc"
