/* -*- 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/>.
 */

#if _MSC_VER > 1000
#pragma once
#endif

#ifndef _IMESSAGE_UTILS_H_
#define _IMESSAGE_UTILS_H_

#include "IMessageC.h"
#include "guid.h"

#define MAPIGUID_H // do not include mapiguid.h
#include <mapix.h>

class CMessage : public virtual IMessage {
public:
	CMessage(BRUTUS::IMessage_ptr BrutusMessage)
		: ref_count_(0),
		  brutus_message_(BRUTUS::IMessage::_duplicate(BrutusMessage))
		{
			InitializeCriticalSection(&critical_section_);
			AddRef();
		};

	STDMETHODIMP QueryInterface(REFIID  riid,
				    LPVOID *ppvObj)
		{
			HRESULT hr = E_NOINTERFACE;
			*ppvObj = 0;

			if ((IID_IUnknown == riid) || (IID_IMAPIProp == riid) || (IID_IMessage == riid)) {
				*ppvObj = (IMessage*)this;
				AddRef();
				hr = S_OK;
			}

			return hr;
		};


	STDMETHODIMP_(ULONG) AddRef()
		{
			EnterCriticalSection(&critical_section_);
			ULONG count = ++ref_count_;
			LeaveCriticalSection(&critical_section_);

			return count;
		};


	STDMETHODIMP_(ULONG) Release()
		{
			EnterCriticalSection(&critical_section_);
			ULONG count = --ref_count_;
			LeaveCriticalSection(&critical_section_);
			if (!count)
				delete this;

			return count;
		};

	virtual HRESULT STDMETHODCALLTYPE SetReadFlag(ULONG ulFlags);

private:
	~CMessage()
		{
			DeleteCriticalSection(&critical_section_);
			brutus_message_->Destroy(0);
		};

	LONG ref_count_;
	CRITICAL_SECTION critical_section_;
	BRUTUS::IMessage_var brutus_message_;
};

#endif //  _ISTREAM_UTILS_H_
