/*
	Copyright (c) 2004 Bram Schoenmakers <bramschoenmakers@kde.nl>
	Coypright (c) 2010 Volker Lanz <vl@fidra.de>

	This library 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 library 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 library; see the file COPYING.LIB.  If not, write to
	the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
	Boston, MA 02110-1301, USA.
*/

#include "kdatepickerpopup.h"

#include <QDateTime>
#include <QWidgetAction>
#include <QCalendarWidget>

class KDatePickerAction : public QWidgetAction
{
	public:
		KDatePickerAction(QCalendarWidget* widget, QObject* parent) :
			QWidgetAction(parent),
			m_CalendarWidget(widget),
			m_OriginalParent(widget->parentWidget())
		{
		}

	protected:
		QWidget* createWidget(QWidget* parent)
		{
			m_CalendarWidget->setParent(parent);
			return m_CalendarWidget;
		}

		void deleteWidget(QWidget* widget)
		{
			if (widget != m_CalendarWidget)
				return;

			m_CalendarWidget->setParent(m_OriginalParent);
		}

	private:
		QCalendarWidget* m_CalendarWidget;
		QWidget* m_OriginalParent;
};

KDatePickerPopup::KDatePickerPopup(const QDate& date, QWidget* parent) :
	QMenu(parent),
	m_CalendarWidget(new QCalendarWidget(this))
{
	connect(m_CalendarWidget, SIGNAL(clicked(const QDate&)), SLOT(slotDateChanged(const QDate&)));
	connect(m_CalendarWidget, SIGNAL(activated(const QDate&)), SLOT(slotDateChanged(const QDate&)));

	m_CalendarWidget->setSelectedDate(date);

	buildMenu();
}

void KDatePickerPopup::buildMenu()
{
	if (isVisible())
		return;

	clear();
	addAction(new KDatePickerAction(m_CalendarWidget, this));
}

QCalendarWidget* KDatePickerPopup::datePicker() const
{
	return m_CalendarWidget;
}

void KDatePickerPopup::setDate(const QDate& date)
{
	m_CalendarWidget->setSelectedDate(date);
}

void KDatePickerPopup::slotDateChanged(const QDate& date)
{
	emit dateChanged(date);
	hide();
}

