/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 1, 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 General Public License for more details.
  
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

/*
* Author : V.Antonevich <v_antonevich@hotmail.com> --- November 2000
*/

/*
* FileViewWatcher.h --- file modification watcher thread
*/

#ifndef __FILEVIEWWATCHWER_H__
#define __FILEVIEWWATCHWER_H__

#include <afxmt.h>

// file modification watcher thread
class KoWatcher
{
// Attributes
private:
	CEvent m_eventStartWatching;
	// signals that watcher thread shall start watching

	CEvent m_eventTerminate;
	// signals that watcher thread should terminate

	CCriticalSection m_section;
	// to synchronize access to data fileds

	TCHAR m_path[_MAX_PATH];
	// path to watch for changes

	bool m_isRecursive;
	// flag to tell if watching for recursive changes

	HWND m_hWnd;
	// window to post notification to

	HANDLE m_handles[3];
	// objects being watched

	DWORD m_count;
	// count of handles

public:
	// messages posted out
	enum 
	{ 
		WM_FILECHANGE = WM_APP + 51,
		// private message for delivering file change notification
	};


// Construction
public:
	KoWatcher(HWND hWnd)
	: m_isRecursive(false)
	, m_hWnd(hWnd)
	{ 
		m_handles[0] = m_eventStartWatching;
		m_handles[1] = m_eventTerminate;
		m_count = 2;
		*m_path = 0;

		// start the thread immediately
		AfxBeginThread(DelegateRun, this);
	}

private:
	// must call SignalTerminate() to destroy this object
	~KoWatcher()
	{}

// Operations
public:
	// signal to start watching for file changes in particular destination
	void SignalStartWatch(LPCTSTR path, bool isRecursive)
	{
		// store parameters
		m_section.Lock();
		_tcscpy(m_path, path);
		m_isRecursive = isRecursive;
		m_section.Unlock();
		m_eventStartWatching.SetEvent();
	}

	// signals to terminate
	void SignalTerminate()
	{
		m_eventTerminate.SetEvent();
	}

// Implementations
private:
	// delegates control to non-static member
	static UINT DelegateRun(LPVOID p)
	{
		KoWatcher* watcher = (KoWatcher*)p;
		return watcher->Run();
	}

	// responds to events until requested to terminate
	UINT Run();

	// starts monitoring 
	bool StartWatch();

	// stops monitoring
	void StopWatch();
};



#endif
// __FILEVIEWWATCHWER_H__