/***************************************************************************
                          CdboDefaultOpt.cpp  -  description
                             -------------------
    begin                : Fri Jun 1 2001
    copyright            : (C) 2001 by Alexy Podolsky
    email                : alexpod@users.sourceforge.net
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/
//#include  <iostream.h>

#include <qcheckbox.h>
#include <qlabel.h>
#include <qradiobutton.h>
#include <qspinbox.h>
#include <qwhatsthis.h>
#include <qtooltip.h>
#include <qdir.h>
#include <qstringlist.h>
#include <qpushbutton.h>
#include <qcolor.h>

#include <kcolorbutton.h>
#include <kaboutdata.h>
#include <kcmodule.h>
#include <klocale.h>
#include <kglobal.h>
#include <kfiledialog.h>
#include <kconfig.h>
#include <kurl.h>
#include <kdirsize.h>
#include <kmessagebox.h>
#include <kprocess.h>
#include <kiconloader.h>
#include <dcopclient.h>
#include <kapplication.h>

#include "CdboDefaultOpt.h"
#include "CdboDefaultOpt.moc"
#include "CdboConfigManager.h"

CdboDefaultOpt::CdboDefaultOpt( QWidget* parent,  const char* name, WFlags  )
    		: CdboDefaultOptBase( parent, name ){
    	
	config = new KConfig("cdbakeovenrc");
	tmpBrowseBtn->setPixmap( BarIcon("fileopen", KIcon::SizeSmall ) );
    	load();
}

/*
 *  Destroys the object and frees any allocated resources
 */
CdboDefaultOpt::~CdboDefaultOpt(){	
}
//---------------------------------------------------------------------------------------------
void CdboDefaultOpt::load(){	
	////////////////////////////
	showWarningsChk->setEnabled(false);
    	config->setGroup("Default Settings");
	tmpLbl->setText(config->readEntry("Tmp Dir", "/tmp/"));
	showMessage = false;
	checkTmpSize();
	
	
	maxSpeedSpn->setValue(config->readNumEntry("Max Write Speed", 14));
	comTimeOutSpn->setValue(config->readNumEntry("Default Command Time Out", 60));

	doOnStartChk->setChecked(config->readBoolEntry("show Main Dialog on start", true));
	scanSysChk->setChecked(config->readBoolEntry("Dont Check Sys", true));
	scanDevicesChk->setChecked(config->readBoolEntry("Auto Scan Devices", true));
	scanScsiChk->setChecked(config->readBoolEntry("Auto Scan SCSI Devices", true));
	minTmpSizeSpn->setValue(config->readNumEntry("Minimum Tmp Size", 700));
	checkSizeChk->setChecked(config->readBoolEntry("Check Tmp Size", true));
	chekSizeSlot();
	
	switch(config->readNumEntry("Level Of Output", CdboConfigManager::StandartOutput)){
		case CdboConfigManager::StandartOutput: stdOutRBtn->setChecked(true); break;
		case CdboConfigManager::CustomOutput: custoutRBtn->setChecked(true); break;
		default:	quiteOutRBtn->setChecked(true); break;
	}
	
	outputLevelSpn->setValue(config->readNumEntry("Custom Level Of Output", 0));
	debugChk->setChecked(config->readBoolEntry("Show Debug Info", false));

	colorDoneBtn->setColor(config->readColorEntry("Process Done Color", &QColor(darkGreen)));
	colorLeftBtn->setColor(config->readColorEntry("Process Left Color", &QColor(white)));
	
	config->setGroup("Notification Messages");	
	//bBuff = config->readBoolEntry("Do Show Type Change Warning", true);
	saveCompilationChk->setChecked(config->readBoolEntry("Do Show Save List Warning", true));
	//showWarningsChk->setChecked(bBuff);
	
	
}
//-----------------------------------------------------------------------------------------------
void CdboDefaultOpt::save(){
	config->setGroup("Default Settings");	
	config->writeEntry("show Main Dialog on start", doOnStartChk->isChecked());
	config->writeEntry("Tmp Dir", tmpLbl->text());
	config->writeEntry("Max Write Speed", maxSpeedSpn->value());
	config->writeEntry("Default Command Time Out", comTimeOutSpn->value());
	
		
	config->writeEntry("Check Tmp Size", checkSizeChk->isChecked());
	config->writeEntry("Dont Check Sys", scanSysChk->isChecked());
	config->writeEntry("Auto Scan Devices", scanDevicesChk->isChecked());
	config->writeEntry("Auto Scan SCSI Devices", scanScsiChk->isChecked());
	
	if(stdOutRBtn->isChecked())
		config->writeEntry("Level Of Output", CdboConfigManager::StandartOutput);
	else if(custoutRBtn->isChecked())
		config->writeEntry("Level Of Output", CdboConfigManager::CustomOutput);
	else	
		config->writeEntry("Level Of Output", CdboConfigManager::QuiteOutput);
	
	config->writeEntry("Custom Level Of Output", outputLevelSpn->value());
	config->writeEntry("Show Debug Info", debugChk->isChecked());
	
	config->writeEntry("Minimum Tmp Size", minTmpSizeSpn->value());
	config->writeEntry("Process Done Color", colorDoneBtn->color());
	config->writeEntry("Process Left Color", colorLeftBtn->color());
	
	config->setGroup("Notification Messages");	
	config->writeEntry("Do Show Save List Warning", saveCompilationChk->isChecked());
	
	config->sync();

	QByteArray data;
	if ( !kapp->dcopClient()->isAttached() )
		kapp->dcopClient()->attach();
	kapp->dcopClient()->send( "cdbakeoven*", "CDBakeOvenApp", "emitSettingsChanged()", data );
}
//----------------------------------------------------------------------------------------------
void CdboDefaultOpt::defaults(){
	config->deleteGroup("Default Settings");
	config->deleteGroup("Notification Messages");	
	showMessage = false;
	load();
}
//----------------------------------------------------------------------------------------------
void CdboDefaultOpt::tmpBrowseSlot(){	
	tempDir = tmpLbl->text();
	if(!tempDir || tempDir == ""){
    		tempDir = KFileDialog::getExistingDirectory(QDir::homeDirPath(),
    			this,
    			I18N_NOOP("Choose Temporary Directory"));
	}
	else{
		tempDir = KFileDialog::getExistingDirectory(tempDir,
    			this,
    			I18N_NOOP("Choose Temporary Directory"));
	}
	tempDir = tempDir.stripWhiteSpace();
	if(!tempDir || tempDir == "") return;
	
	QDir dir(tempDir);
	if(!dir.exists()) return;
	
	checkTmpSize();
	
	if(checkSizeChk->isChecked())	
		return;
	
	tmpLbl->setText(tempDir);
	QToolTip::add(tmpLbl, I18N_NOOP("Using: '" + tempDir +
		"'as temporary directory to store disc image in."));
}
//------------------------------------------------------------------------------------------
void CdboDefaultOpt::customOutSlot(){
	enableCustOut(true);
}
//------------------------------------------------------------------------------------------
void CdboDefaultOpt::quiteOutSlot(){
	enableCustOut(false);
}
//------------------------------------------------------------------------------------------
void CdboDefaultOpt::stdOutSlot(){
	enableCustOut(false);
}
//------------------------------------------------------------------------------------------
void CdboDefaultOpt::enableCustOut(bool yes){
	debugChk->setEnabled(yes);
	outputLbl->setEnabled(yes);
	outputLevelSpn->setEnabled(yes);
}
//------------------------------------------------------------------------------------------
void CdboDefaultOpt::chekSizeSlot(){
	bool yes = checkSizeChk->isChecked();
	minLbl->setEnabled(yes);
	minTmpSizeSpn->setEnabled(yes);
}
//---------------------------------------------------------------------------------------------
void CdboDefaultOpt::checkTmpSize(){
	cdboProc = new KProcess();
	*cdboProc << "df" << "-m" << tempDir;

	connect(cdboProc, SIGNAL(processExited(KProcess *)),
      			this, SLOT(sizeCheckProcessDoneSlot(KProcess *)));
 	connect(cdboProc, SIGNAL(receivedStdout (KProcess *, char *, int)),
		this, SLOT(receivedSizeMessageSlot(KProcess *, char *, int)));
	
	cdboProc->start(KProcess::NotifyOnExit, KProcess::AllOutput);
	
}	
//---------------------------------------------------------------------------------------------
void CdboDefaultOpt::showWarningsSlot(){
	config->setGroup("Notification Messages");
	bool yes = showWarningsChk->isChecked();
	config->writeEntry("Do Show Type Change Warning", yes);
	if(yes)
		saveCompilationChk->setChecked(yes);
}
//---------------------------------------------------------------------------------------------
void CdboDefaultOpt::receivedSizeMessageSlot(KProcess *, char *buffer, int buflen){	
	if(buflen <= 0) return;
	
	QString buff(buffer);
	buff = buff.left(buflen);	
	QStringList comOutput(QStringList::split("\n",buff));
	comOutput = QStringList::split(" ", comOutput[1]);
	buff = comOutput[3].simplifyWhiteSpace();
	
	
	config->setGroup("Default Settings");	
	config->writeEntry("tmp Size", buff.toInt());
	
	//cerr << "tmp Size = " << buff.toInt() << endl;
	
	if(!showMessage){
		showMessage = true;
		return;
	}
	
	if(!checkSizeChk->isChecked())
		return;

	
	if(buff.toInt() < minTmpSizeSpn->value()){	
 		int result = KMessageBox::warningContinueCancel(this,I18N_NOOP(
      		"This directory has less space than the minimum required. " \
      		"Use it anyway?"),
           	I18N_NOOP("Please confirm"),
           	QString("Yes"));
      	if(result != KMessageBox::Continue)
      		return;
	}
			
	tmpLbl->setText(tempDir);
	QToolTip::add(tmpLbl, I18N_NOOP("Using: '" + tempDir +
		"' as the temporary directory to store the disc image."));    	
}
//---------------------------------------------------------------------------------------------
void CdboDefaultOpt::sizeCheckProcessDoneSlot(KProcess *){
	delete cdboProc;
}
//---------------------------------------------------------------------------------------------
int CdboDefaultOpt::buttons() {
	return KCModule::Default|KCModule::Apply|KCModule::Cancel|KCModule::Ok|KCModule::Help;
}
//---------------------------------------------------------------------------------------------
QString CdboDefaultOpt::quickHelp() const{
	return I18N_NOOP("CD Bake Oven Default Settings.");
}
//---------------------------------------------------------------------------------------------
const KAboutData* CdboDefaultOpt::aboutData() const
{

	KAboutData *myAboutData = new KAboutData(I18N_NOOP("cdbakeoven"),
					I18N_NOOP("Default settings for CD Bake Oven - CD creation tool for KDE."),
                  0, 0, KAboutData::License_GPL,
                  "(c) 2001 - 2002 Alex Podolsky");

    myAboutData->addAuthor("Alex Podolsky", 0, "alexpod@users.sf.net");

    return myAboutData;
}

//---------------------------------------------------------------------------------------------
extern "C"{
    KCModule *create_cdbodefaultopt(QWidget *parent, const char *name){
        KGlobal::locale()->insertCatalogue("cdbakeoven");
        return new CdboDefaultOpt(parent, name);
    }

}
