/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2014  Georg Rudoy
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **********************************************************************/

#include "notificationsmanager.h"
#include <QTimer>
#include <util/xpc/util.h>
#include <interfaces/an/constants.h>
#include "todostorage.h"

namespace LeechCraft
{
namespace Otlozhu
{
	NotificationsManager::NotificationsManager (TodoStorage *storage)
	: QObject (storage)
	, Storage_ (storage)
	, NextEventTimer_ (new QTimer (this))
	{
		NextEventTimer_->setSingleShot (true);
		connect (NextEventTimer_,
				SIGNAL (timeout ()),
				this,
				SLOT (handleTimer ()));

		connect (Storage_,
				SIGNAL (itemAdded (int)),
				this,
				SLOT (readjustTimer ()));
		connect (Storage_,
				SIGNAL (itemUpdated (int)),
				this,
				SLOT (readjustTimer ()));
		connect (Storage_,
				SIGNAL (itemRemoved (int)),
				this,
				SLOT (readjustTimer ()));
		readjustTimer ();
	}

	void NotificationsManager::handleTimer ()
	{
		const QString& notify = tr ("%1 is due now!").arg (NextEvent_->GetTitle ());
		auto e = Util::MakeNotification ("Otlozhu", notify, PInfo_);

		e.Additional_ ["org.LC.AdvNotifications.SenderID"] = "org.LeechCraft.Otlozhu";
		e.Additional_ ["org.LC.AdvNotifications.EventCategory"] = AN::CatOrganizer;
		e.Additional_ ["org.LC.AdvNotifications.EventID"] = "org.LC.Plugins.Otlozhu.EventDue/" + NextEvent_->GetID ();
		e.Additional_ ["org.LC.AdvNotifications.VisualPath"] = QStringList (NextEvent_->GetTitle ());

		e.Additional_ ["org.LC.AdvNotifications.EventType"] = AN::TypeOrganizerEventDue;
		e.Additional_ ["org.LC.AdvNotifications.FullText"] = notify;
		e.Additional_ ["org.LC.AdvNotifications.ExtendedText"] = notify;
		e.Additional_ ["org.LC.AdvNotifications.Count"] = 1;

		emit gotEntity (e);

		QTimer::singleShot (1100,
				this,
				SLOT (readjustTimer ()));
	}

	void NotificationsManager::readjustTimer ()
	{
		NextEvent_.reset ();
		NextEventTimer_->stop ();

		QDateTime min;
		const auto& now = QDateTime::currentDateTime ();

		for (int i = 0, size = Storage_->GetNumItems (); i < size; ++i)
		{
			auto item = Storage_->GetItemAt (i);
			if (item->GetPercentage () == 100)
				continue;

			if (!item->GetDueDate ().isValid ())
				continue;

			const auto& due = item->GetDueDate ();
			if ((!min.isValid () || due < min) && due > now)
			{
				min = due;
				NextEvent_ = item;
			}
		}

		if (!min.isValid ())
			return;

		int secsDiff = now.secsTo (min);
		if (secsDiff > std::numeric_limits<int>::max () / 10000)
			QTimer::singleShot (std::numeric_limits<int>::max () / 10,
					this,
					SLOT (readjustTimer ()));
		else
			NextEventTimer_->start (secsDiff * 1000);
	}
}
}
