//globalview.cpp

#include <afxwin.h>
#include "resource.h"
#include "search.h"
#include "spellvar.h"
#include "spell1.h"
#include "CSpellBook.h"
#include "roll.h"
#include "main.h"

// mappa messaggi
BEGIN_MESSAGE_MAP(CGlobalViewDialog, CDialog)
	ON_WM_DESTROY()
	ON_NOTIFY(TVN_SELCHANGED, IDC_TREE1, OnViewSpellClick )
	ON_BN_CLICKED(ID_ADD, OnAddSpell)
END_MESSAGE_MAP()

//metodi privati

//metodi pubblici

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

	CImageList *pImageList=new CImageList;
	pImageList->Create(16, 16, ILC_COLOR4, 3, 1);
	pImageList->Add(::AfxGetApp()->LoadIcon(IDI_VIEW0));	// caster normal	0
	pImageList->Add(::AfxGetApp()->LoadIcon(IDI_VIEW1));	// level normal		1
	pImageList->Add(::AfxGetApp()->LoadIcon(IDI_VIEW2));	// spell normal		2
	pImageList->Add(::AfxGetApp()->LoadIcon(IDI_VIEW0S));	// caster select	3
	pImageList->Add(::AfxGetApp()->LoadIcon(IDI_VIEW1S));	// level select		4
	pImageList->Add(::AfxGetApp()->LoadIcon(IDI_VIEW2S));	// spell select		5

	m_Tree.SetImageList(pImageList, TVSIL_NORMAL);

	return TRUE;
}

void CGlobalViewDialog::SetTree(CStringArray &m_Caster)
{
	for(int cont=0; cont<m_Caster.GetSize(); cont++)
	{
		CSearchDir sd;
		CString locaz=m_Caster[cont]+"//*.*";
		HTREEITEM item=m_Tree.InsertItem(m_Caster[cont], 0, 3);
		sd.DirFull(&m_Tree, locaz, item);
	}

	UpdateData(FALSE);
}

void CGlobalViewDialog::OnCancel()
{
	DestroyWindow();
}

// metodi protetti

void CGlobalViewDialog::OnViewSpellClick(NMHDR *pNot, LRESULT *res)
{
	if(!m_Tree.GetChildItem(m_Tree.GetSelectedItem()) && m_Caller==SPELL)
	{
		DEFSPELL spell;
		spell.Caster=m_Tree.GetItemText(m_Tree.GetParentItem(m_Tree.GetParentItem(m_Tree.GetSelectedItem())));
		spell.School=0;
		spell.Level=ALL;
		spell.Name=m_Tree.GetItemText(m_Tree.GetSelectedItem());

		
		::SendMessage(((CMainWindow*)AfxGetMainWnd())->m_Spell->m_hWnd, WM_USERSPELL, 0, (LPARAM) &spell);
	}
}

void CGlobalViewDialog::DoDataExchange(CDataExchange *pDX)
{
	DDX_Control(pDX, IDC_TREE1, m_Tree);
}


void CGlobalViewDialog::OnDestroy()
{
	m_Tree.DeleteAllItems();
	delete m_Tree.GetImageList(TVSIL_NORMAL);
}


void CGlobalViewDialog::PostNcDestroy()
{
	if(m_Caller==SPELL)
	{
		((CMainWindow *) AfxGetMainWnd())->m_Spell->m_pgvd = NULL;
		((CMainWindow *) AfxGetMainWnd())->m_Spell->CasterType().EnableWindow();
	}
	delete this;
}


void CGlobalViewDialog::OnAddSpell()
{
	if(!m_Tree.GetChildItem(m_Tree.GetSelectedItem()))
	{
		DEFSPELL spell;
		spell.Caster=m_Tree.GetItemText(m_Tree.GetParentItem(m_Tree.GetParentItem(m_Tree.GetSelectedItem())));
		spell.School=0;
		spell.Level=m_Tree.GetItemText(m_Tree.GetParentItem(m_Tree.GetSelectedItem()));
		spell.Name=m_Tree.GetItemText(m_Tree.GetSelectedItem());

		
		::SendMessage(((CMainWindow*)AfxGetMainWnd())->GetSafeHwnd(), WM_USERADDBOOK, 0, (LPARAM) &spell);
	}
}
