#include "Depend.h"

// constructor
Depend::Depend()
{
}

// destructor
Depend::~Depend()
{
}

// clear timestamps record
void Depend::Clear(void)
{
	_fileTimes.Clear();
}

// check for dependency files
// return true if target must be rebuilt
// false otherwise
bool Depend::Check(String const &objPath)
{
	// if target not there, must be rebuilt
	if(!FileExists(objPath))
		return true;
	
	// get obj timestamp
	Time t = FileGetTime(objPath);
	
	// get dependency file
	String depPath = ForceExt(objPath, ".d");
	
	// if no dependency file, must return true
	if(!FileExists(depPath))
		return true;
	
	// read dependencies
	FileIn f(depPath);
	f.GetLine();
	while(!f.IsEof())
	{
		String s = TrimBoth(f.GetLine());
		int is = s.GetCount() - 1;
		while(is && (s[is] == ' ' || s[is] == '\\' || s[is] == ':'))
			is--;
		s.Trim(is + 1);
		if(s.IsEmpty())
			continue;
		int idx = _fileTimes.Find(s);
		if(idx < 0)
		{
			_fileTimes.Add(s, FileGetTime(s));
			idx = _fileTimes.GetCount() - 1;
		}
		// if dependency is newer, must rebuild
		if(_fileTimes[idx] > t)
			return true;
	}
	return false;
}
