// TextSearchCOM.cpp : Implementation of CTextSearchCOM


#include <atlsafe.h>
#include "stdafx.h"
#include "TextSearchCOM.h"
#include "FileManager.h"
#include "SearchManager.h"

typedef std::vector<std::string> files;

// CTextSearchCOM



STDMETHODIMP CTextSearchCOM::searchText(SAFEARRAY * searchStrings, BSTR searchDirectory, BSTR searchOption, SAFEARRAY ** matchedFiles)
{
	// get all text files from the directory tree
	files _allFiles;
	files _matchedFiles;

	FileManager fmObj;
	std::wstring ws(searchDirectory, SysStringLen(searchDirectory));
	_allFiles = fmObj.lookUpFiles(ws.c_str);

	// search strings in all the text files
	SearchManager smObj;
	if (searchOption == L"ANY")
		smObj.setOption(false);
	else
		smObj.setOption(true);

	LONG lBound, uBound;
	SafeArrayGetLBound(searchStrings, 1, &lBound);
	SafeArrayGetUBound(searchStrings, 1, &uBound);
	LONG count = uBound - lBound + 1;  // bounds are inclusive
	BSTR* raw;
	SafeArrayAccessData(searchStrings, (void**)&raw);
	std::vector<std::string> allStrings(raw, raw + count);
	SafeArrayUnaccessData(searchStrings);	// When no longer need "raw".

	_matchedFiles = smObj.matchFound(_allFiles, allStrings);

	CComSafeArray<BSTR> _files;
	for each (std::string _aFile in _matchedFiles)
	{
		_files.Add(CComBSTR(_aFile.c_str()));
	}
	*matchedFiles = _files.Detach();

	return S_OK;
}
