// FileDlg.cpp : implementation file
//

#include "stdafx.h"
#include "mw4gameed.h"
#include "FileDlg.h"
#include "ConfirmDlg.h"
#include <io.h>
#include <direct.h>

/////////////////////////////////////////////////////////////////////////////
// CFileDlg dialog
extern CMW4GameEdApp theApp;


CFileDlg::CFileDlg(CWnd* pParent /*=NULL*/)
: CDialog(CFileDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CFileDlg)
	//}}AFX_DATA_INIT
}

CFileDlg::~CFileDlg()
{
}

void CFileDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CFileDlg)
	DDX_Control(pDX, IDC_FILEDLGNUMOBJEDIT, m_NumObj);
	DDX_Control(pDX, IDC_FILEDLGMAPNAMEEDIT, m_MapName);
	DDX_Control(pDX, IDC_FILEDLGLIST, m_FileList);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CFileDlg, CDialog)
//{{AFX_MSG_MAP(CFileDlg)
ON_BN_CLICKED(IDFILEDLGDELETE, OnFiledlgdelete)
ON_BN_CLICKED(IDFILEDLGOPEN, OnFiledlgopen)
ON_LBN_SELCHANGE(IDC_FILEDLGLIST, OnSelchangeFiledlglist)
ON_LBN_DBLCLK(IDC_FILEDLGLIST, OnDblclkFiledlglist)
ON_WM_CLOSE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFileDlg message handlers

BOOL CFileDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();
	
	SetWindowText("Open Mission File");
	((CButton*)(GetDlgItem(IDFILEDLGOPEN)))->ShowWindow(SW_SHOW);
	/*
	MString path = Working_Directory;
	path += "\\Content\\Missions\\*.*";
	Directory *directory;
	directory = new Directory(path, true);
	Check_Object(directory);
	
	  Stuff::IsolateDirectory(&path);
	  
		Check_Object(directory);
		delete directory;
		
	*/
	LoadMissionList();
	
	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

void CFileDlg::LoadMissionList()
{
	ClearListData();
	
	
	Stuff::NotationFile build_file("Content\\MechWarrior4.build");
	Page *core_page = build_file.FindPage("");
	if (core_page)
	{
		Check_Object(core_page);
		Page::NoteIterator *core_notes = core_page->MakeNoteIterator();
		Check_Object(core_notes);
		Note *core_note;
		while ((core_note = core_notes->ReadAndNext()) != NULL)
		{
			Check_Object(core_note);
			NotationFile map_file;
			core_note->GetEntry(&map_file);
			Page *maps_page = map_file.FindPage("");
			Check_Object(maps_page);
			Page::NoteIterator *map_notes = maps_page->MakeNoteIterator();
			Check_Object(map_notes);
			Note *map_note;
			while ((map_note = map_notes->ReadAndNext()) != NULL)
			{
				Check_Object(map_note);
				NotationFile mission_file;
				map_note->GetEntry(&mission_file);
				Page *missions_page = mission_file.FindPage("");
				if(missions_page)
				{
					Check_Object(missions_page);
					Page::NoteIterator *mission_notes = missions_page->MakeNoteIterator();
					Check_Object(mission_notes);
					Note *mission_note;
					while ((mission_note = mission_notes->ReadAndNext()) != NULL)
					{
						CString misname;	
						misname=mission_note->GetName();
						misname=misname.Left(misname.ReverseFind('.'));
						misname=misname.Mid(misname.ReverseFind('\\')+1);
						int index = m_FileList.AddString(misname);
						CString path;
						char *p;
						path.Format("Content\\Missions\\%s\\%s.instance",misname,misname);
						p = new char[path.GetLength() + 1];
						strcpy(p,(LPCSTR)path);
						m_FileList.SetItemDataPtr(index,p);
						
					}
				}
			}
		}
	}
	
	
	
	
}

void RemoveFolder(char* folderName)
{
	struct _finddata_t file;
	long hFile;
	
	char path[MAX_PATH],fileName[MAX_PATH];
	sprintf(path,"%s\\*.*",folderName);
	
	if((hFile = _findfirst(path,&file)) != -1L)
	{
		do
		{
			if (file.name[0] == '.')
				continue;
			
			sprintf(fileName,"%s\\%s",folderName,file.name);
			if (file.attrib & _A_SUBDIR)
			{
				RemoveFolder(fileName);
				continue;
			}
			SetFileAttributes(fileName,FILE_ATTRIBUTE_NORMAL);
			remove(fileName);
		}
		while(_findnext(hFile,&file) == 0);
		
		_rmdir(folderName);
	}
}

void CFileDlg::OnFiledlgdelete() 
{
	int authorization = 0;
	char missionName[MAX_PATH];
	m_FileList.GetText(m_FileList.GetCurSel(),missionName);
	
	if (strstr(theApp.missionFileName,missionName))
	{
		if (MessageBox("If you delete the currently loaded file, you will not be able to save it afterwards. Are you sure you want to permenantly delete this file?",		// Localize
			"Mission Delete Warning",MB_YESNO) == IDNO) 
		{
			return;
		}
		authorization = IDOK;
		theApp.OnFileClose();
	}
	
	struct _finddata_t file;
	long hFile;
	
	if ((hFile = _findfirst("Content\\resources.build",&file)) == -1L)
		STOP (("Could not find Content\\Resources.build. Please reinstall"));	// Localize
	
	if (file.attrib & _A_RDONLY)
	{
		if (MessageBox("Content\\resources.build is marked read only. Would you like to change the file to writable and continue?",
			"Resource Error",MB_YESNO) == IDNO)
		{
			MessageBox("Unable to remove mission.","Mission Delete Error");
			return;
		}
		SetFileAttributes("Content\\resources.build",FILE_ATTRIBUTE_NORMAL);
	}
	
	if (authorization == 0)
	{
		CConfirmDlg dlg(CONFIRM_FILEDELETE);
		
		dlg.m_Title = "File Delete Confirmation";			// Localize
		dlg.m_MessageText = "Are you sure you want to permanently remove this file?";	// Localize
		authorization = dlg.DoModal();
	}
	if (authorization == IDOK)
	{
		char path[MAX_PATH];
		sprintf(path,"Content\\Missions\\%s",missionName);
		RemoveFolder(path);
		
		LoadMissionList();
		
		FILE* oldFile, *newFile;
		
		if ((oldFile = fopen("Content\\Resources.build","r")) == NULL)
		{
			MessageBox("Unable to open Content\\Resource.build.  The mission has been deleted but you will probably get a warning the next time you start.","Mission Delete Error");	// Localize
			return;
		}
		if ((newFile = fopen("Content\\Resources.del","w")) == NULL)
		{
			MessageBox("Unable to create temperary file.  The mission has been deleted but you will probably get a warning the next time you start.","Mission Delete Error");	// Localize
			return;
		}
		char buffer[512];
		do
		{
			fgets(buffer,511,oldFile);
			if (feof(oldFile))
				break;
			
			if (strstr(strlwr(buffer),strlwr(missionName)) || buffer[0] == 10)
			{
				continue;
			}
			fputs(buffer,newFile);
		}
		while (1);
		fclose(oldFile);
		fclose(newFile);
		remove("Content\\Resources.build");
		rename("Content\\Resources.del","Content\\Resources.build");
	}
}

void CFileDlg::OnFiledlgopen() 
{
	m_PathName = (char*)m_FileList.GetItemDataPtr(m_FileList.GetCurSel());
	ClearListData();
	CDialog::OnOK();
}

void CFileDlg::OnSelchangeFiledlglist() 
{
	int index = m_FileList.GetCurSel();
	char* path = (char*)m_FileList.GetItemDataPtr(index);
	
	if (path)
	{
		NotationFile file(path);
		
		char drive[_MAX_DRIVE],dir[_MAX_DIR],fname[_MAX_FNAME],ext[_MAX_EXT],contentFile[MAX_PATH];
		const char* mapFile;
		_splitpath(path,drive,dir,fname,ext);
		_makepath(contentFile,drive,dir,fname,"contents");
		
		Page *page = file.GetPage(fname);
		Check_Object(page);
		page->GetEntry("Map",&mapFile,true);
		
		_splitpath(mapFile,drive,dir,fname,ext);
		m_MapName.SetWindowText(fname);
		
		NotationFile propFile(contentFile);
		
		char numString[8];
		NotationFile::PageIterator *pages = propFile.MakePageIterator();
		Check_Object(pages);
		m_NumObj.SetWindowText(itoa(pages->GetSize(),numString,10));
		delete pages;
	}
	else
	{
		// You should never get here
		MessageBox("Could not associate an instance file with that mission","File Error");
	}
}

void CFileDlg::OnDblclkFiledlglist() 
{
	OnFiledlgopen();
}

char* CFileDlg::GetPathName()
{
	return ((char*)LPCTSTR(m_PathName));
}

void CFileDlg::ClearListData()
{
	while (m_FileList.GetCount())
	{
		char* path = (char*)m_FileList.GetItemDataPtr(0);
		if (path)
			delete [] path;
		m_FileList.DeleteString(0);
	}
}

void CFileDlg::OnCancel() 
{
	ClearListData();
	CDialog::OnCancel();
}
