/***************************************************************************
                          CdboCompilationView.cpp  -  description
                             -------------------
    begin                : Sun Nov 18 2001
    copyright            : (C) 2001 by Alex Podolsky
    email                : alexpod@users.sf.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 <qgrid.h>
#include <qdir.h>

#include <kprocess.h>
#include <kmessagebox.h>
#include <kfiledialog.h>
#include <klocale.h>

/* cdbakeoven includes */
#include "CdboCompilationView.h"
#include "CdboCompilationView.moc"

CdboCompilationView::CdboCompilationView(QWidget *parent, const char *name) :
			QGrid(3, parent, name){
	
	listFileName = "";
	saved = true;
}

CdboCompilationView::~CdboCompilationView(){
}

 //==============================
void CdboCompilationView::showTargetControl(bool doShow){
	if(!doShow)
		getControl()->hide();
	else
		getControl()->show();
}
//==============================
void CdboCompilationView::showEstimate(bool doShow){
	if(!doShow)
		getEstimate()->hide();
	else
		getEstimate()->show();
}
//====================================
void CdboCompilationView::saveRemoveAndLoad(QString fileToOpen){
	if(!saveAndRemove())
		return;
	
	doLoad(fileToOpen);
	listFileName = fileToOpen;
	saved = true;
	emitGotCaption();
}
//====================================
bool CdboCompilationView::saveAndRemove(){
	if(isEmpty())
		return true;
	
	  if(saved){
	 	removeAll();
		return true;
	 }
	KConfig *config = new KConfig("cdbakeovenrc");
	config->setGroup("Notification Messages");	
	if(!config->readBoolEntry("Do Show Save List Warning", true)){
		removeAll();
		listFileName = "";
  		delete config;
		return true;
	}
	delete config;
	int result = KMessageBox::warningYesNoCancel(this,
					i18n("Compilation file list has been modified, would you like to save it?"),
        				i18n("Save File List?"),
        				i18n("&Yes"),
        				i18n("&No"));
    	switch(result) {
    		case KMessageBox::No:{
			removeAll();
			listFileName = "";
			return true;
		}
		case KMessageBox::Cancel:{
			return false;
		}
		case KMessageBox::Yes:{
			if(!save())
				return false;
			removeAll();
			listFileName = "";
			return true;
		}	
    	}
    	return true;
}
//===========================================================
void CdboCompilationView::removeAll(){
	listFileName = "";
	saved = true;
	emitGotCaption();
}
//=====================================================
bool CdboCompilationView::saveAs(){
	if(isEmpty())
		return true;
		
	QString fileToOpen = listFileName;
	if(!fileToOpen.isNull() && fileToOpen != "")
		fileToOpen = fileToOpen.left(fileToOpen.findRev("/", -2));
	else
		fileToOpen = QDir::homeDirPath(); //QString::null;
		
		
	fileToOpen = KFileDialog::getSaveFileName(fileToOpen,
				i18n("*.cdbo|CD List Files (*.cdbo)\n*|All files"),
				this,
				i18n("Save CD List File As..."));
	if(!fileToOpen || fileToOpen == "")
		return false;
	if(fileToOpen.find(".cdbo", -5, false) == -1)
		fileToOpen = fileToOpen.stripWhiteSpace() + ".cdbo";
	
	doSave(fileToOpen);
	return true;
}

//============================
bool CdboCompilationView::save(){
	if(isEmpty() || saved )
		return true;

    	if(!listFileName.isNull() && listFileName != ""){
    		doSave(listFileName);
    		return true;
    	}
    	else
    		return saveAs();
}
//==============================
void CdboCompilationView::contentsModified(){
	saved = false;
	emitGotCaption();
}
//---------------------------------------------------------------------------------------------
void CdboCompilationView::popUpSettings(int type){
	
	KShellProcess *cdboProc = new KShellProcess();
	switch(type){
		case AudioSettings:
			*cdboProc << "kcmshell audiocd";
			break;
		case DevicesSettings:
			*cdboProc << "kcmshell cdbocdromdevices kcmdf";
			break;
		case ImageSettings:
			*cdboProc << "kcmshell cdboisoopt";
			break;
		default:
			*cdboProc << "kcmshell cdbodefaultopt";
			break;
	}
	connect(cdboProc, SIGNAL(processExited(KProcess*)), this, SLOT(kcmshellDone(KProcess*)));
	if(!cdboProc->start(KProcess::NotifyOnExit))
		cerr << "Failed to start\n\n";
}
//---------------------------------------------------------------------------------------------
void CdboCompilationView::kcmshellDone(KProcess *proc){
	delete proc;
}
//---------------------------------------------------------------------------------------------
void CdboCompilationView::showEmptyError(){
	KMessageBox::detailedSorry(this,
			i18n("Compilation list is empty!"),
			i18n("You must populate the compilation list with the files you\nwish to have on your new CD."\
				" To accomplish this, just\ndrag the source files or directories from one of the upper\n(source) views down"\
				" into the compilation view. This option\ncan then be used to burn your files on to CD."));
		return;
}
//---------------------------------------------------------------------------------------------
bool CdboCompilationView::checkOverwrite(QString fName){
	QFileInfo d(fName);
	if(d.exists()){
		int result = KMessageBox::warningContinueCancel(this,
			i18n("A file with the same name already exists! "\
			"Click 'Cancel' to display the 'Settings Dialog' and "\
			"change the ISO name, OR overwrite the existing one."),
			i18n("Overwrite Existing?"),
			i18n("&Overwrite"));
		switch(result) {
			case KMessageBox::Continue:
				return true;
    			default:{
				popUpSettings(CdboCompilationView::ImageSettings);
				return false;
			}
		}
    	}
	return true;
}
//---------------------------------------------------------------------------------------------
bool CdboCompilationView::checkDirSize(){
	KConfig *config = new KConfig("cdbakeovenrc");
	config->setGroup("Default Settings");

	if(config->readBoolEntry("Check Tmp Size", true)){
		int size = config->readNumEntry("tmp Size", -1);

		if(size == -1){
			int result = KMessageBox::warningContinueCancel(this,
					i18n("Unable to determine temporary directory size! Would you "\
					"like to display the 'Settings Dialog' to choose the temporary directory now?"),
     				i18n("Display Settings Dialog Now?"),
     				i18n("&Yes"));
    			switch(result) {
    				case KMessageBox::Continue:{
					popUpSettings(CdboCompilationView::DefaultSettings);
					delete config;
    					return true;
				}
			}///////
		}
		else{
			//cerr << "size = " << size << endl;
			//cerr << "getSize() = " << getSize() << endl;
			if(size < getSize()){
				KMessageBox::error(this,
						i18n("The temporary directory does not have enough space available " \
						"to store the disk image. Please remove some files from the list "\
						"or choose another location from the 'Settings Dialog'."));

    				delete config;
     			return false;
			}
			config->writeEntry("Image Size", getSize());
			config->sync();
		}
	}
	delete config;
	return true;
}
