//file search.cpp

#include "search.h"

// Classe CSearchDir

// Funzioni pubbliche

CString CSearchDir::GetDir(CString& partenza, CString& nomefile, CString& original)
{
	CString result;
	CFileFind trova;
	if (nomefile.GetLength()==0)
		return result;

	CString dir=partenza + "\\*.*";
	BOOL find = trova.FindFile((LPCTSTR) dir);
	while(find)
	{
		find=trova.FindNextFile();
		if (trova.IsDirectory())
		{
			if (trova.IsDots())
				continue;
			CString newdir=partenza + "\\" + trova.GetFileName();
			result = GetDir(newdir, nomefile, original);
			if (result.GetLength()!=0)
				return result;
		}

		if (trova.GetFileName()==nomefile)
		{
			result=trova.GetFilePath();
			int pos = result.Find((LPCTSTR) partenza);
			if (pos < 0)
				::MessageBox(NULL, "ERRORE in ricerca file!!","ERRORE DI RICERCA", MB_OK);
			else
			{
				int offset = result.GetLength()-pos; // -1 per contare il '\'
				return result.Right(offset);
			}
		}
	}
	return result;
}

void CSearchDir::DirFull(CTreeCtrl *tree, const char * locazione, HTREEITEM parent)
{
    CFileFind trova;
    BOOL found = trova.FindFile(locazione);
    while (found)
    {
        found = trova.FindNextFile();
		if (!trova.IsDots())
		{
			if(trova.IsDirectory())
			{
				CString newdir = locazione;
				newdir=newdir.Left(newdir.GetLength()-3);		// locazione contiene sempre ...\\*.*
				newdir+=trova.GetFileName()+"\\*.*";
				HTREEITEM newitem=tree->InsertItem(trova.GetFileName(), 1, 4, parent);
				DirFull(tree, (LPCTSTR)newdir, newitem);
			}
			else
			{
				CString tmp = trova.GetFileName();
				int pos = tmp.Find('.');
				if (pos!=-1)
					tmp=tmp.Left(pos);
				tree->InsertItem(tmp, 2, 5, parent, TVI_SORT);
			}
		}
    }
}
