/***************************************************************************
    begin                : Mon Jan 28 2002
    copyright            : (C) 2002 by Christian Hubinger
    email                : chubinger@irrsinnig.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

// StdLib includes
#include <iostream>
#include <unistd.h>
#include <sys/stat.h>

// QT includes
#include "tqtextstream.h"
#include "tqfile.h"
#include "tqxml.h"
#include "tqregexp.h"
#include "tqptrlist.h"
#include "tqmessagebox.h"
#include <tqstringlist.h>
#include <tqvbox.h>
#include <tqlabel.h>

// KDE includes
#include <kdebug.h>
#include <kstandarddirs.h>
#include <tdefiledialog.h>
#include <kurl.h>
#include <tqfiledialog.h>
#include <tdeio/job.h>
#include <tdeio/netaccess.h>
#include <tdelocale.h>
#include <kprocess.h>
#include <tdeapplication.h>
#include <tdeconfig.h>
#include <tdemessagebox.h>
#include <tdetempfile.h>

// My includes
#include "../version.h"
#include "kmfdoc.h"
#include "iptchain.h"
#include "iptrule.h"
#include "iptable.h"
#include "netfilterobject.h"
#include "kmferror.h"
#include "kmfconfig.h"
#include "kmferrorhandler.h"
#include "kmfnetwork.h"
#include "kmftarget.h"

namespace KMF {

KMFDoc::KMFDoc( NetfilterObject *parent, const char *name ) : NetfilterObject( parent, name ) {
	kdDebug() << "KMFDoc::KMFDoc( TQObject *parent, const char *name ) : NetfilterObject( parent )" << endl;
/*	NetfilterObject::setName( i18n( "Unnamed Document" ) );
	NetfilterObject::setDescription( i18n( "No Description Available" ) );*/
	m_newSavePathNeeded = true;
	m_url = KURL();
	resetUrl();
}

KMFDoc::~KMFDoc() {}

KURL& KMFDoc::url() {
	return m_url;
}

bool KMFDoc::newSavePathNeeded() {
	return m_newSavePathNeeded;
}

const TQString& KMFDoc::docName() {
	if ( m_url.isEmpty() ) {
		return *( new TQString( i18n("Unnamed Document") ) );
	} else { 
		return *( new TQString( m_url.fileName() ) );
	}
}

void KMFDoc::resetUrl() {
	m_url.setHost( TQString() );
	m_url.setPath( TQString() );
	m_url.setProtocol( TQString() );
	NetfilterObject::setName( i18n( "Unnamed Document" ) );
	NetfilterObject::setDescription( i18n( "No Description Available" ) );
	m_newSavePathNeeded = true;
}

void KMFDoc::updateView() {
	kdDebug() << "void KMFDoc::upateView()" << endl;
}

KMFError* KMFDoc::exportXMLRuleset( bool promptFile, bool asTemplate ) {
	kdDebug() << "bool KMFDoc::exportXMLRuleset( promptFile " << promptFile << " asTemplate " << asTemplate << " )" << endl;
	// KMFError err 
	
	kdDebug() << "Curr DocURL:: " << this->url().url() << endl;
	if ( this->newSavePathNeeded() ) {
		promptFile = true;
	}
	KURL saveUrl = this->url();
	kdDebug() << "promptFile: " << promptFile << endl;
	if ( promptFile ) {
		// KURL url;
		// bool chooseTemlate = false;
		TQString path = ":";
		TQString filter = "*.kmfrs|KMyFirewall IPTables Ruleset (*.kmfrs)";
		
		TQString desc = i18n("KMyFirewall IPTables Ruleset (*.kmfrs)");
		TQString tdesc = i18n("KMyFirewall IPTables Ruleset Template (*.tkmfrs)");
		
		TQString gdesc = i18n("KMyFirewall Generic Ruleset (*.kmfgrs)");
		TQString tgdesc = i18n("KMyFirewall Generic Ruleset Template (*.tkmfgrs)");
		
		TQString ndesc = i18n("KMyFirewall Network (*.kmfnet)");
		
		
		
		TDEStandardDirs std_dir;
		TQString tmp_dir = std_dir.findResourceDir( "data", "kmyfirewall/templates/" );
		TQDir dir( tmp_dir + "/kmyfirewall/templates/" );
		
		
		filter = TQString("*.kmfnet|" + ndesc );
		
/*		saveUrl = KFileDialog::getSaveURL( ":", "*.kmfnet|KMyFirewall Network (*.kmfnet)\n*.kmfgrs|KMyFirewall Generic Ruleset(*.kmfgrs)\n*.kmfrs|KMyFirewall IPTables Ruleset(*.kmfrs)" );*/
		
		saveUrl = KFileDialog::getSaveURL( ":", getFileDialogFilter() );
		
		// saveUrl = KFileDialog::getSaveURL( path, filter );
		TQString filename = saveUrl.fileName();
		if ( saveUrl.fileName().isEmpty() ) {
			return new KMFError();
		}
		int answer = 0;
		while ( answer != KMessageBox::Yes ) {
			if ( TDEIO::NetAccess::exists( saveUrl, false, TDEApplication::kApplication()->mainWidget() ) ) {
				if ( answer == 4 ) {
					return exportXMLRuleset( promptFile, asTemplate );
				} else {
					answer = KMessageBox::questionYesNo( 0, i18n( "<qt>File <b>%1</b> already exists!</p>"
														"<p><b>Overwrite the existing file?</b></p></qt>" ).arg( saveUrl.url() ) );
				}
			} else {
				answer = 3;
			}
		}
	}
	return  exportXMLRuleset( saveUrl );
}


KMFError* KMFDoc::exportXMLRuleset( const KURL& url ) {
 	kdDebug() << "bool KMFIPTDoc::exportXMLRuleset(const KURL& " << url.url() << " )" << endl;
	KTempFile file;
	const TQString& xml = getXMLSniplet();
// 	kdDebug() << "Writing XML:\n " << xml << endl;
	if ( file.name() != TQString() ) {
		TQFile f( file.name() );
		f.remove();
		bool isWriteable = f.open( IO_ReadWrite );
		if ( isWriteable ) {
			TQTextStream ts( &f );
			ts << xml << endl;
			f.flush();
			f.close();
			
			if ( ! TDEIO::NetAccess::upload( file.name(), url, TDEApplication::kApplication()->mainWidget() ) ) {
				kdDebug() << "Coudn't save File: " << url.url() << endl;
				m_err->setErrType( KMFError::NORMAL );
				m_err->setErrMsg( i18n( "<qt><p><b>Saving <i>%1</i> Failed.</b></p>"
				                        "<p>Please make sure that you have the permissions to write to this Directory.<br>"
				                        "If you are working with remotely stored files "
				                        "make sure that the target host and the directory is reachable. "
				                        "</p></qt>" ).arg( url.url() ) );
				file.unlink();
				return m_err;
			}
			file.unlink();
			

			m_err -> setErrType( KMFError::OK );
			m_err -> setErrMsg( "" );
			kdDebug() << "KMFDoc: Wrote " << url.url() << endl;
			m_url = url;
			m_newSavePathNeeded = false;
			return m_err;
		} else {
			// generate retrun error object
			m_err -> setErrType( KMFError::NORMAL );
			const TQString& msg = i18n( "Opening file %1 for writing failed.\n"
			                           "Please make sure that you are logged in as root" ).arg( file.name() );
			m_err -> setErrMsg( msg );
			file.unlink();
			return m_err;
		}

	} else {
		// generate retrun error object
		m_err -> setErrType( KMFError::NORMAL );
		const TQString& msg = i18n( "Opening file %1 for writing failed.\n"
		                           "Please make sure that you are logged in as root" ).arg( file.name() );
		m_err -> setErrMsg( msg );
		file.unlink();
		return m_err;
	}
	// generate retrun error object
	m_err -> setErrType( KMFError::FATAL );
	const TQString& msg = i18n( "File to save = TQString(). This is a bug." );
	m_err -> setErrMsg( msg );
	file.unlink();
	return m_err;
}

const TQString& KMFDoc::getXMLSniplet() {
	return  *( new TQString( getDOMTree().toString() ) );
}

const TQString& KMFDoc::getXMLRuleset() {
	return getXMLSniplet();
}

}
#include "kmfdoc.moc"
