/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */

/*
 *  Copyright (C) 2008 OMC Denmark ApS.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma warning(disable : 4996)

#include "advise_utils.h"
#include "conv_utils.h"

// The return value goes to MAPI so I think that we should
// return S_OK even if an error occured.
STDMETHODIMP_(ULONG) CMAPIAdviseSink::OnNotify(ULONG cNotify,
					       LPNOTIFICATION lpNotifications)
{
	bool ok = false;

	// convert and send via brutus_sink_..
	BRUTUS::seq_NOTIFICATION_var not_list;
	try {
		not_list = new BRUTUS::seq_NOTIFICATION;
	}
	catch (std::bad_alloc &) {
		BRUTUS_LOG_ERR("No memory");
		brutus_sink_->InternalError(BRUTUS::BRUTUS_MAPI_E_NOT_ENOUGH_MEMORY);
		return S_OK;
	}
	try {
		ok = notify_mapi_to_brutus(cNotify,
					   lpNotifications,
					   not_list.out(),
					   mapi_session_,
					   poa_);
		if (!ok)
			BRUTUS_LOG_CRITICAL("False returned");
	}
	catch (...) {
		BRUTUS_LOG_CRITICAL("Exception caught");
	}
	if (!ok) {
		BRUTUS_LOG_CRITICAL("Could not convert Notification from MAPI to BRUTUS");
		try {
			brutus_sink_->InternalError(BRUTUS::BRUTUS_INTERNAL_ERROR);
		}
		catch (...) {
			BRUTUS_LOG_CRITICAL("Exception caught");
		}
		not_list->length(0);
	}

	try {
		if (ok)
			brutus_sink_->OnNotify(not_list.in());
	}
	catch (...) {
		BRUTUS_LOG_CRITICAL("Exception caught");
	}

	return (ULONG)S_OK;
}
