/* -*- 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 _PROGRESS_UTILS_H_
#define _PROGRESS_UTILS_H_

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

class CMAPIProgress : public virtual IMAPIProgress {
public:
	CMAPIProgress(BRUTUS::IMAPIProgress_ptr BrutusProgress)
		: ref_count_(0), min_(1), max_(1000), flags_(MAPI_TOP_LEVEL)
		{
			brutus_progress_ = BrutusProgress;
			InitializeCriticalSection(&critical_section_);
			AddRef();
		};

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

			if ((IID_IUnknown == riid) || (IID_IMAPIAdviseSink == riid)) {
				*ppvObj = (IMAPIAdviseSink*)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;
		};

	HRESULT __stdcall Progress(ULONG ulValue,
				   ULONG ulCount,
				   ULONG ulTotal);

	HRESULT __stdcall GetFlags(ULONG *lpulFlags);

	HRESULT __stdcall GetMax(ULONG *lpulMax);

	HRESULT __stdcall GetMin(ULONG *lpulMin);

	HRESULT __stdcall SetLimits(LPULONG lpulMin,
				    LPULONG lpulMax,
				    LPULONG lpulFlags);

private:
	~CMAPIProgress()
		{
			if (!CORBA::is_nil(brutus_progress_))
				brutus_progress_->Destroy(0);
			DeleteCriticalSection(&critical_section_);
		};

	LONG ref_count_;
	CRITICAL_SECTION critical_section_;
	BRUTUS::IMAPIProgress_var brutus_progress_;

	// Only used if progress is NIL
	ULONG min_;
	ULONG max_;
	ULONG flags_;
};

#endif //  _PROGRESS_UTILS_H_
