
#include "editorwindow.h"

#include <kaction.h>
#include <kapp.h>
#include <kfiledialog.h>
#include <kmenubar.h>
#include <kmessagebox.h>
#include <kstdaccel.h>
#include <kstdaction.h>
#include <qfile.h>
#include <qpopupmenu.h>
#include <qtextstream.h>

EditorWindow::EditorWindow()
{
	/*
	KAction *new_action = new KAction(
		"&New",
		"filenew",
		KStdAccel::key(KStdAccel::New),
		this,
		SLOT(newFile()),
		this);
	*/

	KAction *new_action = KStdAction::openNew(
		this, SLOT(newFile()), this);

	KAction *open_action = new KAction(
		"&Open...",
		"fileopen",
		KStdAccel::key(KStdAccel::Open),
		this,
		SLOT(openFile()),
		this);

	KAction *save_action = new KAction(
		"&Save...",
		"filesave",
		KStdAccel::key(KStdAccel::Save),
		this,
		SLOT(saveFile()),
		this);

	KAction *quit_action = new KAction(
		"&Quit...",
		"stop",
		KStdAccel::key(KStdAccel::Quit),
		KApplication::kApplication(),
		SLOT(quit()),
		this);
	
	QPopupMenu *file_menu = new QPopupMenu;
	menuBar()->insertItem("&File", file_menu);
	
	new_action->plug(file_menu);
	file_menu->insertSeparator();
	open_action->plug(file_menu);
	save_action->plug(file_menu);
	file_menu->insertSeparator();
	quit_action->plug(file_menu);

	new_action->plug(toolBar());	
	open_action->plug(toolBar());
	save_action->plug(toolBar());
	quit_action->plug(toolBar());
	
	m_pEditor = new KEdit(this);
	setView(m_pEditor);
}


EditorWindow::~EditorWindow()
{
	if(m_pEditor->isModified())
	{
		int rc = KMessageBox::warningYesNo(
			this,
			"There are unsaved changes. Do you want to save\n"
			"the changes?");

		if(rc == KMessageBox::Yes)
			saveFile();
	}
}


void
EditorWindow::newFile()
{
	if(m_pEditor->isModified())
	{
		int rc = KMessageBox::warningYesNo(
			this,
			"There are unsaved changes. Are you sure want to\n"
			"start a new file?");

		if(rc == KMessageBox::No)
			return;
	}

	m_pEditor->clear();
	m_pEditor->setModified(false);
}


void
EditorWindow::openFile()
{
	QString file = KFileDialog::getOpenFileName();

	if( ! file.isEmpty())
	{
		QFile f(file);

		if(f.open(IO_ReadOnly))
		{
			QTextStream s(&f);
			m_pEditor->insertText(&s);
			m_pEditor->setModified(false);
		}
	}
}


void
EditorWindow::saveFile()
{
	QString file = KFileDialog::getSaveFileName();

	if( ! file.isEmpty())
	{
		QFile f(file);

		if(f.open(IO_WriteOnly | IO_Truncate))
		{
			QTextStream s(&f);
			m_pEditor->saveText(&s);
			m_pEditor->setModified(false);
		}
	}
}
