// DepDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ResourceBrowser.h"
#include "DepDlg.h"
#include <MW4\MW4.hpp>
using namespace MechWarrior4;

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

/////////////////////////////////////////////////////////////////////////////
// CDepDlg dialog


CDepDlg::CDepDlg(const char *resname,CWnd* pParent /*=NULL*/)
: CDialog(CDepDlg::IDD, pParent)
{
	ResName=resname;
	//{{AFX_DATA_INIT(CDepDlg)
	//}}AFX_DATA_INIT
}


void CDepDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDepDlg)
	DDX_Control(pDX, IDC_DEPTREE, m_DepTree);
	DDX_Control(pDX, IDC_CALLTREE, m_CallTree);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CDepDlg, CDialog)
//{{AFX_MSG_MAP(CDepDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDepDlg message handlers

BOOL CDepDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();
	FillDeps(ResName);
	FillCallers(ResName);
	
	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

void CDepDlg::FillDeps(const char *resname,HTREEITEM par)
{
	HTREEITEM itm=m_DepTree.InsertItem(resname,par);
	
	short rfilenum;

	for(rfilenum=0;rfilenum<FreeId;rfilenum++)
	{
	ResourceFile *rfile=ResourceManager::Instance->GetResourceFile(rfilenum);
	Resource res(resname,rfile);
	if(res.DoesResourceExist())
	{
		FileDependencies deps;
		res.GetFileDependencies(&deps);
		
		deps.m_fileNameStream.Rewind();
		deps.m_fileNameStream.AdvancePointer(strlen((char *)deps.m_fileNameStream.GetPointer())+1);
		
		while(deps.m_fileNameStream.GetBytesRemaining())
		{
			const char *ptr=(const char *)deps.m_fileNameStream.GetPointer();
			FillDeps(ptr,itm);
			deps.m_fileNameStream.AdvancePointer(strlen(ptr)+1);
		}
	}
	}
}

void CDepDlg::FillCallers(const char *resname,HTREEITEM par)
{
	HTREEITEM itm=m_CallTree.InsertItem(resname,par);
	
	Resource res(resname);
	if(res.DoesResourceExist())
	{
		Resource curres;
		curres.First(NULL);
		while(curres.ReadAndNext())
		{
			if(curres.GetResourceID().GetFileID()==TexturesResourceFileID ||
				curres.GetResourceID().GetFileID()==CoreResourceFileID ||
				curres.GetResourceID().GetFileID()==PropsResourceFileID
				)
			{	
				FileDependencies deps;
				curres.GetFileDependencies(&deps);
				deps.m_fileNameStream.Rewind();
				if(deps.m_fileNameStream.GetBytesRemaining())
				{
					char *cresname=(char *)deps.m_fileNameStream.GetPointer();
						deps.m_fileNameStream.AdvancePointer(strlen(cresname)+1);
				
				while(deps.m_fileNameStream.GetBytesRemaining())
				{
					const char *ptr=(const char *)deps.m_fileNameStream.GetPointer();
					
					if(!strcmpi(ptr,resname)) 
						FillCallers(cresname,itm);
					deps.m_fileNameStream.AdvancePointer(strlen(ptr)+1);
				}
				}
			}	
		}
		
		
	}
	
	
}
