/*
** 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 : Alexandre Parenteau <aubonbeurre@hotmail.com> --- December 1997
 */

/*
 * MultiFiles.h --- class to store multiple files by directory
 */

#include "stdafx.h"

#include <stdlib.h>
#include <string.h>

#include "MultiFiles.h"
#include "CvsArgs.h"
#include "AppConsole.h"
#include "CPStr.h"

#include <errno.h>

#ifdef WIN32
#	ifdef _DEBUG
#	define new DEBUG_NEW
#	undef THIS_FILE
	static char THIS_FILE[] = __FILE__;
#	endif
#endif /* WIN32 */

void MultiFilesEntry::setdir(const char *newdir)
{
	dir = newdir;
}

void MultiFilesEntry::add(const char *file, const FSSpec *spec)
{
	FileEntry entry(file, spec);
	files.push_back(entry);
}

void MultiFiles::newdir(const char *dir)
{
	MultiFilesEntry entry(dir);
	dirs.push_back(dir);
}

void MultiFiles::newfile(const char *file, const FSSpec *spec)
{
	if(dirs.size() == 0)
		return;

	MultiFilesEntry & entry = dirs[dirs.size() - 1];
	entry.add(file, spec);
}

bool MultiFiles::next(void)
{
	if(pos == -1)
		pos = 0;
	else
		++pos;

	return (size_t)pos < dirs.size();
}

char *MultiFiles::add(CvsArgs & args)
{
	if(pos < 0 || (size_t)pos >= dirs.size())
		return 0L;

	MultiFilesEntry & entry = dirs[pos];
	std::vector<FileEntry>::const_iterator i;
	for(i = entry.files.begin(); i != entry.files.end(); ++i)
	{
		args.addfile((*i).file, entry.dir, &(*i).spec);
	}
	return entry.dir;
}

bool MultiFiles::get (int index, CStr & path, CStr & fileName)
{
	if(pos < 0 || (size_t)pos >= dirs.size())
		return false;

	MultiFilesEntry & entry = dirs[pos];
	if(index < 0 || (size_t)index >= entry.files.size())
		return false;

	path = entry.dir;
	fileName = entry.files[index].file;
	return true;
}

int MultiFiles::NumFiles(void) const
{
	int locpos = pos;
	if(locpos == -1)
		locpos = 0;
	if((size_t)locpos >= dirs.size())
		return 0;

	const MultiFilesEntry & entry = dirs[locpos];
	return entry.files.size();
}

void MultiFiles::reset()
{
	dirs.erase(dirs.begin(), dirs.end());
	pos = -1;
}
