// AnimGenerateDlg.cpp : implementation file
//

#include "stdafx.h"
#include <atlbase.h>
#include "AnimGenerate.h"
#include "AnimGenerateDlg.h"
#include "suffixdlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAnimGenerateDlg dialog

CAnimGenerateDlg::CAnimGenerateDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CAnimGenerateDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CAnimGenerateDlg)
	m_editStandpose = _T("");
	m_editDestination = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CAnimGenerateDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAnimGenerateDlg)
	DDX_Control(pDX, IDC_EDIT_STANDPOSE, m_ctlEditStandpose);
	DDX_Control(pDX, IDC_EDIT_PREFIX, m_ctlEditPrefix);
	DDX_Control(pDX, IDC_EDIT_DESTINATION, m_ctlEditDestination);
	DDX_Text(pDX, IDC_EDIT_STANDPOSE, m_editStandpose);
	DDX_Text(pDX, IDC_EDIT_DESTINATION, m_editDestination);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAnimGenerateDlg, CDialog)
	//{{AFX_MSG_MAP(CAnimGenerateDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BROWSE_STANDPOSE, OnBrowseStandpose)
	ON_BN_CLICKED(IDC_BROWSE_DESTINATION, OnBrowseDestination)
	ON_BN_CLICKED(IDC_SUFFIX, OnSuffix)
	ON_BN_CLICKED(IDC_EXECUTE, OnExecute)
	ON_WM_CLOSE()
	ON_WM_DESTROY()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAnimGenerateDlg message handlers

BOOL CAnimGenerateDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	this->LoadSettings();
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CAnimGenerateDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CAnimGenerateDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CAnimGenerateDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CAnimGenerateDlg::OnBrowseStandpose() 
{
	CFileDialog dlg(TRUE,NULL,NULL,0,"Max Files (*.max)|*.max||",this);
	char szDir[MAX_PATH];
	GetCurrentDirectory(MAX_PATH,szDir);
	dlg.m_ofn.lpstrInitialDir = szDir;
	if (IDOK == dlg.DoModal())
	{
		this->m_editStandpose = dlg.GetPathName();
		this->m_ctlEditStandpose.SetWindowText(this->m_editStandpose);
	}
}

void CAnimGenerateDlg::OnBrowseDestination() 
{
	this->m_editDestination = theApp.BrowseDirectory(NULL,this);
	this->m_ctlEditDestination.SetWindowText(this->m_editDestination);
}

void CAnimGenerateDlg::OnSuffix() 
{
	CSuffixDlg dlg;
	dlg.m_strList.AddHead(&theApp.m_listSuffix);
	if (IDOK == dlg.DoModal())
	{
		theApp.m_listSuffix.RemoveAll();
		theApp.m_listSuffix.AddHead(&dlg.m_strList);
	}
}

void CAnimGenerateDlg::OnExecute() 
{
	// Make sure the three strings actually have values	
	this->UpdateData();
	if (this->m_editDestination.IsEmpty())
	{
		MessageBox("Destination required.","",MB_OK);
		return;
	}
	if (this->m_editStandpose.IsEmpty())
	{
		MessageBox("Original required.",this->m_editStandpose,MB_OK);
		return;
	}
	CString strPrefix;
	this->m_ctlEditPrefix.GetWindowText(strPrefix);
	if (strPrefix.IsEmpty())
	{
		MessageBox("prefix required.",strPrefix,MB_OK);
		return;
	}
	
	// load the standpose into memory
	HANDLE hFile;
	if (NULL == (hFile = CreateFile(this->m_editStandpose,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL)))
	{
		MessageBox("Original file does not exist.","",MB_OK);
		return;
	}
	DWORD dwSize = GetFileSize(hFile,NULL);
	if (0xFFFFFFFF == dwSize)
	{
		MessageBox("Original file does not exist.",this->m_editStandpose,MB_OK);
		return;
	}
	BYTE *pData = new BYTE[dwSize];
	DWORD dwResultSize;
	if (!ReadFile(hFile,pData,dwSize,&dwResultSize,NULL))
	{
		MessageBox("Error reading original file.",this->m_editStandpose,MB_OK);
		CloseHandle(hFile);
		if (pData) delete pData;
		return;
	}
	CloseHandle(hFile);

	if (dwResultSize != dwSize)
	{
		MessageBox("Error reading original file - file read size error.",this->m_editStandpose,MB_OK);
	}

	// create destination directory
	CString szDestination;
	this->m_ctlEditDestination.GetWindowText(szDestination);


	CreateDirectory(szDestination,NULL);
/*
// Directory may already exist
	if (!CreateDirectory(szDestination,NULL))
	{
		MessageBox("Error creating destination directory.",szDestination,MB_OK);
		if (pData) delete pData;
		return;
	}
*/
	// for each name in the suffix list, append to prefix to create name, then check that that name is not being used
	// and write the standpose to that name
	POSITION pos = theApp.m_listSuffix.GetHeadPosition();
	int iStatus = IDOK;
	while (pos&&(iStatus != IDABORT))
	{
		CString str = szDestination+"\\"+strPrefix+"_"+theApp.m_listSuffix.GetAt(pos)+".Max";
		if (((VOID *)0xffffffff) == (hFile = CreateFile(str,GENERIC_WRITE,FILE_SHARE_WRITE,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL)))
		{
			iStatus = MessageBox("Destination file already exists.",str,MB_ABORTRETRYIGNORE);
		}
		else
		{
			if (!WriteFile(hFile,pData,dwSize,&dwResultSize,NULL))
			{
				iStatus = MessageBox("Error Writing destination file.",str,MB_ABORTRETRYIGNORE);
			}
			if (dwResultSize != dwSize)
			{
				iStatus = MessageBox("Error writing destination file - file write size error.",str,MB_ABORTRETRYIGNORE);
			}
		}
		CloseHandle(hFile);
		if (!(iStatus == IDRETRY))
			theApp.m_listSuffix.GetNext(pos);
	}

	// done
	if (pData) delete pData;
}

void CAnimGenerateDlg::LoadSettings()
{
	
	char szKey[] = "SOFTWARE\\Microsoft\\MW4Tools\\AnimGenerate";
	CRegKey regKey;
	if (ERROR_SUCCESS != regKey.Open(HKEY_CURRENT_USER,szKey))
	{
		return;
	}

	DWORD dwSize;
	char szData[MAX_PATH];

	dwSize = MAX_PATH;
	if (ERROR_SUCCESS != regKey.QueryValue(szData,"Destination",&dwSize))
	{
		//goto DONE;
	}
	this->m_ctlEditDestination.SetWindowText(szData);
	this->m_editDestination = CString(szData);

	dwSize = MAX_PATH;
	if (ERROR_SUCCESS != regKey.QueryValue(szData,"Standpose",&dwSize))
	{
	}
	this->m_ctlEditStandpose.SetWindowText(szData);
	this->m_editStandpose = CString(szData);

	dwSize = MAX_PATH;
	if (ERROR_SUCCESS != regKey.QueryValue(szData,"Prefix",&dwSize))
	{
	}
	this->m_ctlEditPrefix.SetWindowText(szData);

	DWORD dwCount = 0;
	if (ERROR_SUCCESS != regKey.QueryValue(dwCount,"SuffixCount"))
	{
	}
	for (DWORD x=0;x<dwCount;x++)
	{
		CString str;
		str.Format("Suffix%i",x);
		dwSize = MAX_PATH;
		if (ERROR_SUCCESS != regKey.QueryValue(szData,str,&dwSize))
		{
		}
		theApp.m_listSuffix.AddHead(szData);
	}

//DONE:
	regKey.Close();

	this->UpdateData();
}

void CAnimGenerateDlg::SaveSettings()
{
	this->UpdateData();
	char szKey[] = "SOFTWARE\\Microsoft\\MW4Tools\\AnimGenerate";

	RegDeleteKey(HKEY_CURRENT_USER,szKey);

	CRegKey regKey;
	if (ERROR_SUCCESS != regKey.Create(HKEY_CURRENT_USER,szKey))
	{
		return;
	}

	if (ERROR_SUCCESS != regKey.SetValue(this->m_editDestination,"Destination"))
	{
//		goto DONE;
	}

	if (ERROR_SUCCESS != regKey.SetValue(this->m_editStandpose,"Standpose"))
	{
//		goto DONE;
	}

	CString str;
	this->m_ctlEditPrefix.GetWindowText(str);
	if (ERROR_SUCCESS != regKey.SetValue(str,"Prefix"))
	{
//		goto DONE;
	}

	int iCount = theApp.m_listSuffix.GetCount();
	if (ERROR_SUCCESS != regKey.SetValue(iCount,"SuffixCount"))
	{
//		goto DONE;
	}
	for (int x=0;x<iCount;x++)
	{
		POSITION pos = theApp.m_listSuffix.FindIndex(x);
		str.Format("Suffix%i",x);
		if (ERROR_SUCCESS != regKey.SetValue(theApp.m_listSuffix.GetAt(pos),str))
		{
	//		goto DONE;
		}
	}

//DONE:
	regKey.Close();
}

void CAnimGenerateDlg::OnClose() 
{
	//this->SaveSettings();	
	CDialog::OnClose();
}

void CAnimGenerateDlg::OnDestroy() 
{
	this->SaveSettings();
	CDialog::OnDestroy();
	
}
