/*
 * Cueplot: a GUI front-end to gnuplot
 * Copyright (C) 2007 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 "RawCommandDialog.h"

#include <QtCore/QCoreApplication>
#if QT_VERSION >= 0x040200
# include <QtGui/QDialogButtonBox>
#endif
#include <QtGui/QHBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QTextEdit>
#include <QtGui/QVBoxLayout>

RawCommandDialog *RawCommandDialog::instance_ = 0;

RawCommandDialog &RawCommandDialog::instance(QWidget *parent)
{
	if (!instance_) {
		instance_ = new RawCommandDialog(parent);
	}
	return *instance_;
}

void RawCommandDialog::destroyInstance()
{
	if (instance_) {
		delete instance_;
		instance_ = 0;
	}
}

RawCommandDialog::RawCommandDialog(QWidget *parent)
: QDialog(parent)
{
	setWindowTitle(tr("Raw Commands") + " - " 
			+ QCoreApplication::applicationName());

	rawTextEdit = new QTextEdit;
#if QT_VERSION >= 0x040100
	rawTextEdit->setAcceptRichText(false);
#endif

	execPushButton = new QPushButton;
	connect(execPushButton, SIGNAL(clicked()), SLOT(accept()));
	execPushButton->setText(tr("&Execute"));
	execPushButton->setDefault(true);
	execPushButton->setEnabled(false);
	connect(rawTextEdit, SIGNAL(textChanged()),
			this, SLOT(setButton()));

	QPushButton *cancelPushButton = new QPushButton;
	connect(cancelPushButton, SIGNAL(clicked()), SLOT(reject()));
	cancelPushButton->setText(tr("&Close"));

	// create layouts
	// assemble layouts
#if QT_VERSION >= 0x040200
	QDialogButtonBox *dialogButtonBox = new QDialogButtonBox;
	dialogButtonBox->addButton(execPushButton,
			QDialogButtonBox::ActionRole);
	dialogButtonBox->addButton(cancelPushButton,
			QDialogButtonBox::RejectRole);
#else
	QHBoxLayout *buttonLayout = new QHBoxLayout;
	buttonLayout->addStretch();
	buttonLayout->addWidget(execPushButton);
	buttonLayout->addWidget(cancelPushButton);
#endif

	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->addWidget(rawTextEdit);
#if QT_VERSION >= 0x040200
	mainLayout->addWidget(dialogButtonBox);
#else
	mainLayout->addLayout(buttonLayout);
#endif

	setLayout(mainLayout);
}

void RawCommandDialog::accept()
{
	emit executed(rawTextEdit->toPlainText());
}

void RawCommandDialog::setButton()
{
	// テキストエディット内が空でなければ、実行ボタンを有効にする
	execPushButton->setEnabled(!rawTextEdit->toPlainText().isEmpty());
}
