/*
 * Cueplot: a GUI front-end to gnuplot
 * Copyright (C) 2007, 2008 Muneyuki Noguchi
 *
 * 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.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation, 
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include "FileLineEdit.h"

#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtCore/QUrl>
#if QT_VERSION >= 0x040200 && !defined(Q_OS_WIN32)
# include <QtGui/QCompleter>
# include <QtGui/QDirModel>
#endif
#include <QtGui/QDropEvent>

FileLineEdit::FileLineEdit(const QString &key, QWidget *parent)
: QLineEdit(parent), key_(key)
{
	// Task Tracker at trolltech.com
	// #185568 QDirModel accesses the floppy drive when shown in a view
#if QT_VERSION >= 0x040200 && !defined(Q_OS_WIN32)
	QCompleter *completer = new QCompleter;
	completer->setModel(new QDirModel(completer));
	setCompleter(completer);
#endif

	if (!key_.isEmpty()) {
		QSettings settings;
		settings.beginGroup("file");
		file_ = settings.value(key_).toString();
		settings.endGroup();
	}
}

FileLineEdit::~FileLineEdit()
{
	if (!key_.isEmpty()) {
		QSettings settings;
		settings.beginGroup("file");
		if (file_ != settings.value(key_).toString()) {
			settings.setValue(key_, file_);
		}
		settings.endGroup();
	}
}

void FileLineEdit::setFile(const QString &file)
{
	file_ = file;
	setText(
#if QT_VERSION >= 0x040200
		QDir::toNativeSeparators(file)
#else
		QDir::convertSeparators(file)
#endif
	);
}

const QString &FileLineEdit::file() const
{
	return file_;
}

void FileLineEdit::dragEnterEvent(QDragEnterEvent *event)
{
	if (event->mimeData()->hasUrls()) {
		event->acceptProposedAction();
	} else {
		QLineEdit::dragEnterEvent(event);
	}
}

void FileLineEdit::dropEvent(QDropEvent *event)
{
	const QMimeData *mimeData = event->mimeData();
	if (mimeData->hasUrls()) {
		setFile(mimeData->urls().at(0).toLocalFile());
		event->acceptProposedAction();
	} else {
		QLineEdit::dropEvent(event);
	}
}
