/* This file is part of the KDE project
   Copyright (C) 2006-2007 Jaroslaw Staniek <js@iidea.pl>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this program; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include "kexicontextmenuutils.h"

#include <tdeactioncollection.h>
#include <tdelocale.h>
#include <kiconloader.h>
#include <tdefiledialog.h>
#include <kimageio.h>
#include <kdebug.h>
#include <tdemessagebox.h>

#include <tqfiledialog.h>
#include <tqapplication.h>

#ifdef TQ_WS_WIN
#include <win32_utils.h>
#include <tderecentdirs.h>
#endif

//! @internal
class KexiImageContextMenu::Private
{
public:
	Private(TQWidget *parent)
	 : actionCollection(parent)
	{
	}

	TDEActionCollection actionCollection;
	TDEAction *insertFromFileAction, *saveAsAction, *cutAction, *copyAction, *pasteAction,
		*deleteAction
#ifdef KEXI_NO_UNFINISHED 
		, *propertiesAction
#endif
		;
};

//------------

KexiImageContextMenu::KexiImageContextMenu(TQWidget* parent)
 : TDEPopupMenu(parent)
 , d( new Private(this) )
{
	setName("KexiImageContextMenu");
	insertTitle(TQString());

	d->insertFromFileAction = new TDEAction(i18n("Insert From &File..."), SmallIconSet("document-open"), 0,
			this, TQ_SLOT(insertFromFile()), &d->actionCollection, "insert");
	d->insertFromFileAction->plug(this);
	d->saveAsAction = KStdAction::saveAs(this, TQ_SLOT(saveAs()), &d->actionCollection);
//	d->saveAsAction->setText(i18n("&Save &As..."));
	d->saveAsAction->plug(this);
	insertSeparator();
	d->cutAction = KStdAction::cut(this, TQ_SLOT(cut()), &d->actionCollection);
	d->cutAction->plug(this);
	d->copyAction = KStdAction::copy(this, TQ_SLOT(copy()), &d->actionCollection);
	d->copyAction->plug(this);
	d->pasteAction = KStdAction::paste(this, TQ_SLOT(paste()), &d->actionCollection);
	d->pasteAction->plug(this);
	d->deleteAction = new TDEAction(i18n("&Clear"), SmallIconSet("edit-delete"), 0,
		this, TQ_SLOT(clear()), &d->actionCollection, "delete");
	d->deleteAction->plug(this);
#ifdef KEXI_NO_UNFINISHED 
	d->propertiesAction = 0;
#else
	insertSeparator();
	d->propertiesAction = new TDEAction(i18n("Properties"), 0, 0,
		this, TQ_SLOT(showProperties()), &d->actionCollection, "properties");
	d->propertiesAction->plug(this);
#endif
	connect(this, TQ_SIGNAL(aboutToShow()), this, TQ_SLOT(updateActionsAvailability()));
}

KexiImageContextMenu::~KexiImageContextMenu()
{
	delete d;
}

void KexiImageContextMenu::insertFromFile()
{
//	TQWidget *focusWidget = tqApp->focusWidget();
#ifdef TQ_WS_WIN
	TQString recentDir;
	TQString fileName = TQFileDialog::getOpenFileName(
		KFileDialog::getStartURL(":LastVisitedImagePath", recentDir).path(), 
		convertKFileDialogFilterToTQFileDialogFilter(KImageIO::pattern(KImageIO::Reading)), 
		this, 0, i18n("Insert Image From File"));
	KURL url;
	if (!fileName.isEmpty())
		url.setPath( fileName );
#else
	KURL url( KFileDialog::getImageOpenURL(
		":LastVisitedImagePath", this, i18n("Insert Image From File")) );
//	TQString fileName = url.isLocalFile() ? url.path() : url.prettyURL();

	//! @todo download the file if remote, then set fileName properly
#endif
	if (!url.isValid()) {
		//focus the app again because to avoid annoying the user with unfocused main window
		if (tqApp->mainWidget()) {
			//focusWidget->raise();
			//focusWidget->setFocus();
			tqApp->mainWidget()->raise();
		}
		return;
	}
	kexipluginsdbg << "fname=" << url.prettyURL() << endl;

#ifdef TQ_WS_WIN
	//save last visited path
//	KURL url(fileName);
	if (url.isLocalFile())
		TDERecentDirs::add(":LastVisitedImagePath", url.directory());
#endif

	emit insertFromFileRequested(url);
	if (tqApp->mainWidget()) {
//		focusWidget->raise();
//		focusWidget->setFocus();
		tqApp->mainWidget()->raise();
	}
}

void KexiImageContextMenu::saveAs()
{
	TQString origFilename, fileExtension;
	bool dataIsEmpty = false;
	emit aboutToSaveAsRequested(origFilename, fileExtension, dataIsEmpty);

	if (dataIsEmpty) {
		kdWarning() << "KexiImageContextMenu::saveAs(): no data!" << endl;
		return;
	}
	if (!origFilename.isEmpty())
		origFilename = TQString("/") + origFilename;

	if (fileExtension.isEmpty()) {
		// PNG data is the default
		fileExtension = "png";
	}
	
#ifdef TQ_WS_WIN
	TQString recentDir;
	TQString fileName = TQFileDialog::getSaveFileName(
		KFileDialog::getStartURL(":LastVisitedImagePath", recentDir).path() + origFilename,
		convertKFileDialogFilterToTQFileDialogFilter(KImageIO::pattern(KImageIO::Writing)), 
		this, 0, i18n("Save Image to File"));
#else
	//! @todo add originalFileName! (requires access to TDERecentDirs)
	TQString fileName = KFileDialog::getSaveFileName(
		":LastVisitedImagePath", KImageIO::pattern(KImageIO::Writing), this, i18n("Save Image to File"));
#endif
	if (fileName.isEmpty())
		return;
	
	if (TQFileInfo(fileName).extension().isEmpty())
		fileName += (TQString(".")+fileExtension);
	kdDebug() << fileName << endl;
	KURL url;
	url.setPath( fileName );

#ifdef TQ_WS_WIN
	//save last visited path
	if (url.isLocalFile())
		TDERecentDirs::add(":LastVisitedImagePath", url.directory());
#endif

	TQFile f(fileName);
	if (f.exists() && KMessageBox::Yes != KMessageBox::warningYesNo(this, 
		"<qt>"+i18n("File \"%1\" already exists."
		"<p>Do you want to replace it with a new one?")
		.arg(TQDir::convertSeparators(fileName))+"</qt>",0, 
		KGuiItem(i18n("&Replace")), KGuiItem(i18n("&Don't Replace"))))
	{
		return;
	}

//! @todo use KURL?
	emit saveAsRequested(fileName);
}

void KexiImageContextMenu::cut()
{
	emit cutRequested();
}

void KexiImageContextMenu::copy()
{
	emit copyRequested();
}

void KexiImageContextMenu::paste()
{
	emit pasteRequested();
}

void KexiImageContextMenu::clear()
{
	emit clearRequested();
}

void KexiImageContextMenu::showProperties()
{
	emit showPropertiesRequested();
}

void KexiImageContextMenu::updateActionsAvailability()
{
	bool valueIsNull = true;
	bool valueIsReadOnly = true;
	emit updateActionsAvailabilityRequested(valueIsNull, valueIsReadOnly);

	d->insertFromFileAction->setEnabled( !valueIsReadOnly );
	d->saveAsAction->setEnabled( !valueIsNull );
	d->cutAction->setEnabled( !valueIsNull && !valueIsReadOnly );
	d->copyAction->setEnabled( !valueIsNull );
	d->pasteAction->setEnabled( !valueIsReadOnly );
	d->deleteAction->setEnabled( !valueIsNull && !valueIsReadOnly );
	if (d->propertiesAction)
		d->propertiesAction->setEnabled( !valueIsNull );
}

TDEActionCollection* KexiImageContextMenu::actionCollection() const
{
	return &d->actionCollection;
}

//static
bool KexiImageContextMenu::updateTitle(TQPopupMenu *menu, const TQString& title, const TQString& iconName)
{
	return KexiContextMenuUtils::updateTitle(menu, title, i18n("Image"), iconName);
}

// -------------------------------------------

//static
bool KexiContextMenuUtils::updateTitle(TQPopupMenu *menu, const TQString& objectName, 
	const TQString& objectTypeName, const TQString& iconName)
{
	if (!menu || objectName.isEmpty() || objectTypeName.isEmpty())
		return false;
	const int id = menu->idAt(0);
	TQMenuItem *item = menu->findItem(id);
	if (!item)
		return false;
	TDEPopupTitle *title = dynamic_cast<TDEPopupTitle *>(item->widget());
	if (!title)
		return false;

/*! @todo look at makeFirstCharacterUpperCaseInCaptions setting [bool]
 (see doc/dev/settings.txt) */
	TQString realTitle( i18n("Object name : Object type", "%1 : %2")
		.arg( objectName[0].upper() + objectName.mid(1) )
		.arg( objectTypeName ));

	if (iconName.isEmpty())
		title->setTitle(realTitle);
	else {
		TQPixmap pixmap(SmallIcon( iconName ));
		title->setTitle(realTitle, &pixmap);
	}
	return true;
}

#include "kexicontextmenuutils.moc"
