// SElectNoteDlg.cpp : implementation file
//

#include "stdafx.h"
#include "SelectNoteDlg.h"
#include "dictionary.h"

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

#define DATE_FORMATE _T("%d.%m.%y %H:%M")
/////////////////////////////////////////////////////////////////////////////
// CSelectNoteDlg dialog

#define APL_SEPARATOR _T("{\\rtf1\\ansi\\ansicpg1251\\deff0\\deflang1049{\\fonttbl{\\f0\\fnil\\b\\fcharset0 Arial;}}{\\colortbl ;\\red0\\green0\\blue128;}\\uc1\\pard\\ql\\cf1\\lang1033\\fs20\\line\\b ======================================================== \\b0\\line\\line\\par }")
#define APL_SEPARATOR_LEVEL _T("{\\rtf1\\ansi\\ansicpg1251\\deff0\\deflang1049{\\fonttbl{\\f0\\fnil\\b\\fcharset0 Arial;}}{\\colortbl ;\\red0\\green0\\blue128;}\\uc1\\pard\\ql\\cf1\\lang1033\\fs20\\line ---------------------------------------------------------------------------------------------------------------- \\line\\line\\par }")
#define APL_AUTOR_DATE(id,author, date, size) _T("{\\rtf1\\ansi\\ansicpg1251\\deff0\\deflang1049{\\fonttbl{\\f0\\fnil\\fcharset1 Arial;}}{\\colortbl ;\\red0\\green0\\blue0;}\\uc1\\pard\\ql\\cf1\\lang1033\\fs")+size+_T("\\b ")+id+_T(". ")+author+_T(" (")+date+_T(")\\b0\\line\\line\\par }")
#define APL_ADD_NOTE  APL_T("Создать новое примечание")
#define APL_DELETE_NOTE  APL_T("Удалить примечание")
#define APL_ADD_NOTE_TO_NOTE  APL_T("Создать ответное примечание")
#define APL_COPY_NOTE  APL_T("Копировать содержимое")



CSelectNoteDlg::CSelectNoteDlg(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CSelectNoteDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSelectNoteDlg)
	//}}AFX_DATA_INIT
	m_api = 0;
	m_inst = 0;
	m_splitter = 0;
	m_notes = 0;
	m_ciNoteToSelect = NULL;
	m_bShowTree=false;
}


void CSelectNoteDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSelectNoteDlg)
	DDX_Control(pDX, IDC_SHOW_IN_TREE, m_show_in_tree);
	DDX_Control(pDX, IDC_DELETE_NOTE, m_del);
	DDX_Control(pDX, IDC_COPY_NOTE, m_copy);
	DDX_Control(pDX, IDC_ANSVER_NOTE, m_ansver);
	DDX_Control(pDX, IDC_ADD_NOTE, m_add);
	DDX_Control(pDX, IDC_NOTES, m_tmp);
	DDX_Control(pDX, IDC_RICHEDIT, m_richedit);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CSelectNoteDlg, CaplResizableDialog)
	//{{AFX_MSG_MAP(CSelectNoteDlg)
	ON_COMMAND(IDC_NOTE_CTRL,OnSelChange)
	ON_BN_CLICKED(IDC_ADD_NOTE, OnAddNote)
	ON_BN_CLICKED(IDC_DELETE_NOTE, OnDeleteNote)
	ON_BN_CLICKED(IDC_COPY_NOTE, OnCopyNote)
	ON_BN_CLICKED(IDC_ANSVER_NOTE, OnAnsverNote)
	ON_COMMAND(WM_SPLITTER_MOVED, OnSplitterMoved)
	ON_WM_CONTEXTMENU()
	ON_BN_CLICKED(IDC_SHOW_IN_TREE, OnShowAll)
	ON_COMMAND(ID_NOTES_ADD, OnAddNote)
	ON_COMMAND(ID_NOTES_DELETE, OnDeleteNote)
	ON_COMMAND(ID_NOTES_ANSVER, OnAnsverNote)
	ON_COMMAND(ID_NOTES_COPY, OnCopyNote)	
	//}}AFX_MSG_MAP
	ON_COMMAND(ID_NOTES_REVOKE, &CSelectNoteDlg::OnNotesRevoke)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSelectNoteDlg message handlers

BOOL CSelectNoteDlg::OnInitDialog() 
{
	CaplResizableDialog::OnInitDialog();
	if(m_api==NULL)
	{
		EndDialog(0);
		return FALSE;
	}

	// предотвращаем потерю модальности после диалога с бочками из aplSocketTransport
	CORRECT_LOOSE_MODAL_ON_CLASS(&(m_api->m_data));

	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
	ModifyStyle(0, WS_MAXIMIZEBOX);   

	m_cancel_btn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancel_btn.SetFlat(FALSE);
	API_DLG_TEST;
	
	CRect r;
	m_tmp.GetWindowRect(r);
	ScreenToClient(r);
	m_tmp.ShowWindow(SW_HIDE);

	/*	Старое создание CaplTreeListCtrlView
	
	CCreateContext pContext;
	CWnd* pFrameWnd =  this;

	pContext.m_pCurrentDoc = new CaplTreeListCtrlDoc;
	pContext.m_pNewViewClass = RUNTIME_CLASS(CaplTreeListCtrlView);
	m_notes =(CaplTreeListCtrlView*)((CFrameWnd*)pFrameWnd)->CreateView(&pContext,IDC_NOTE_CTRL);
	ASSERT(m_notes);
	m_notes->OnInitialUpdate();
	m_notes->ShowWindow(SW_NORMAL);
	m_notes->MoveWindow(&r);
	*/
	
/*	m_notes = (CaplTreeListCtrlView*)(RUNTIME_CLASS(CaplTreeListCtrlView)->CreateObject());
	ASSERT(m_notes);
	m_notes->Create(0,0,WS_BORDER|WS_VISIBLE|WS_CHILD|AFX_WS_DEFAULT_VIEW,r,this,IDC_NOTE_CTRL);
	m_notes->OnInitialUpdate();
	m_notes->MoveWindow(&r);*/
	m_notes=CaplTreeListCtrlView::CreateTreeListView(this,r,IDC_NOTE_CTRL);
	
	m_notes->m_tree.m_dlg=(CaplResizableDialog*)this;
	m_notes->m_bAutofit = true;
	m_notes->m_tree.m_wndHeader.SetAutofit();
	m_notes->m_tree.m_bSortRoot = true;
	m_notes->m_tree.SetColumnDate(1);
	
	m_notes->m_tree.SetImageList(aplGetInstImageList(),TVSIL_NORMAL);

	CString descr;
	m_notes->m_tree.InsertColumn(0, APL_T("Текст"),LVCFMT_LEFT,200);
	m_notes->m_tree.InsertColumn(1, APL_T("Дата"),LVCFMT_LEFT,100);
	m_notes->m_tree.InsertColumn(2, APL_T("Автор"),LVCFMT_LEFT,150);
	m_splitter = new CaplSplitterBar;
	CRect r1, r2;
	m_notes->GetWindowRect(r1);
	m_richedit.GetWindowRect(r2);
	r.top = r1.top;
	r.bottom = r1.bottom;
	r.left = r1.right;
	r.right = r2.left;
	m_splitter->Create(WS_VISIBLE|WS_CHILD,r,this,IDC_SPLITTER_BAR);
	m_splitter->SetPanes(m_notes,&m_richedit);
	LoadData();
	if(mode==APL_VIEW_MODE)
	{
		CRect r1, r2;
		m_richedit.GetWindowRect(r1);
		m_notes->GetWindowRect(r2);
		ScreenToClient(r1);
		ScreenToClient(r2);
		r1.left = r2.left;
		m_notes->ShowWindow(SW_HIDE);			
		m_richedit.MoveWindow(r1);
		AddNotes(m_inst);
	}
	AddAnchor(IDCANCEL,BOTTOM_RIGHT);
	AddAnchor(IDC_NOTE_CTRL,TOP_LEFT,BOTTOM_LEFT);
	AddAnchor(IDC_SPLITTER_BAR,TOP_LEFT,BOTTOM_LEFT);
	AddAnchor(IDC_RICHEDIT,TOP_LEFT,BOTTOM_RIGHT);
	AddAnchor(IDC_SHOW_IN_TREE,BOTTOM_LEFT);
	AddAnchor(IDC_COPY_NOTE,TOP_RIGHT);
	m_add.SetIcon(GetAplTableIco(APL_TABLE_NOTE));
	m_add.SetTooltipText(APL_ADD_NOTE);
	m_del.SetIcon(GetAplTableIco(APL_TABLE_NOTE_DELETE));
	m_del.SetTooltipText(APL_DELETE_NOTE);
	m_copy.SetIcon(GetAplTableIco(APL_TABLE_COPY));
	m_copy.SetTooltipText(APL_COPY_NOTE);
	m_ansver.SetIcon(GetAplTableIco(APL_TABLE_NOTE_NOTE));
	m_ansver.SetTooltipText(APL_ADD_NOTE_TO_NOTE);
	m_show_in_tree.SetCheck(1);

	// ищем примечание, которое нужно выделить
	if(m_ciNoteToSelect)
	{
		HTREEITEM hItem = m_notes->m_tree.GetRootItem();
		FindNoteToSelect(hItem, hItem);

		m_notes->m_tree.SetItemState(hItem, TVIS_SELECTED, TVIS_SELECTED);
		m_notes->m_tree.SelectItem(hItem);
		OnSelChange();
	}

	if(!m_bShowTree) { OnShowAll();}
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CSelectNoteDlg::FindNoteToSelect(HTREEITEM hParent, HTREEITEM &hItemSelect)
{
	HTREEITEM hItem = NULL;
	CaplInstance *cit = NULL;

	while(hParent)
	{
		cit = (CaplInstance*)m_notes->m_tree.GetItemData(hParent);
		if(cit == m_ciNoteToSelect)
			hItemSelect = hParent;

		if(m_notes->m_tree.ItemHasChildren(hParent))
		{
			hItem = m_notes->m_tree.GetChildItem(hParent);
			FindNoteToSelect(hItem, hItemSelect);
		}

		hParent = m_notes->m_tree.GetNextSiblingItem(hParent);
	}
}

void CSelectNoteDlg::SetRTF(CaplInstance *note)
{
	if(note==0) return;
	long size=0;
	m_api->m_data.NET_GetBlobSize(note,m_api->m_appr_mgr.a_note_source, size);
	if(size==0)
	{
		m_richedit.SetRTF(_T(""));
		return;
	}
	BYTE *c = new BYTE[size+1];
	m_api->m_data.NET_LoadBlob2Memory(note,m_api->m_appr_mgr.a_note_source,c,size);
	c[size]='\0';
	CString rtf((char*)c);
	delete c;
	m_richedit.SetRTF(rtf);
}

bool CSelectNoteDlg::AddRTF(CaplInstance *inst, bool first)
{
	if(inst==0) return false;
	long size;
	m_api->m_data.NET_GetBlobSize(inst,m_api->m_appr_mgr.a_note_source, size);
	BYTE *c =  new BYTE[size];
	m_api->m_data.NET_LoadBlob2Memory(inst,m_api->m_appr_mgr.a_note_source,c,size);
	CString rtf;
	rtf += (const char*)c;
	if(!first) m_richedit.SetRTF(APL_SEPARATOR,APL_RC_SELECTION);
	CString date, author;
	m_api->m_data.GetAttr(inst,m_api->m_appr_mgr.a_note_date, date);
	COleDateTime time;
	aplString2Date(date,time);
	date = time.Format(DATE_FORMATE);
	CaplInstance *pers;
	m_api->m_data.GetAttr(inst,m_api->m_appr_mgr.a_note_author, pers);
	m_api->m_appr_mgr.GetPersonName(pers,author);
	CString l = _T("1");
	CString fsize = _T("24");
	author = APL_AUTOR_DATE(l,author, date, fsize);
	m_richedit.SetRTF(author,APL_RC_SELECTION);
	m_richedit.SetRTF(rtf,APL_RC_SELECTION);
	delete c;
	return true;
}

void CSelectNoteDlg::SortExtent(aplExtent &ext)
{
	if(ext.Size<=1) return;
	CaplInstance *mn = 0;
	CString str;
	CString str1;
	CaplAttr *attr=m_api->m_categ_mgr.a_note_date;
	bool old = ext.Unique;
	ext.Unique = false;
	int gap = ext.Size/2, eo, i;
	do 
	{
		do 
		{
			eo=0;
			for(i =0; i<ext.Size-gap;i++)
			{
				m_api->m_data.GetAttr(ext[i],attr,str1);
				m_api->m_data.GetAttr(ext[i+gap],attr,str);
				if(str1>str)
				{
					CaplInstance *tmp=ext[i];
					ext.SetAt(i,ext[i+gap]);
					ext.SetAt(i+gap,tmp);
					eo = 1;
				}
			}
			
		} while(eo);	
	} while(gap=gap/2);
	ext.Unique = old;
}

bool CSelectNoteDlg::ItemChange(NM_TREEVIEW* pNMTreeView)
{
	OnSelChange();

	return true;
}

void CSelectNoteDlg::OnSelChange()
{
	CaplInstance *inst = (CaplInstance*)m_notes->m_tree.GetItemData(m_notes->m_tree.GetSelectedItem());
	if(!inst) return; 
	SetRTF(inst);	
}


void CSelectNoteDlg::OnAddNote() 
{
	if(m_api->m_appr_mgr.CreateNote(m_inst))
		LoadData();
}

void CSelectNoteDlg::OnDeleteNote() 
{
	CaplInstance *note = (CaplInstance*)m_notes->m_tree.GetItemData(m_notes->m_tree.GetSelectedItem());
	if(!note) return; 
	if(!m_api->m_data.IsKindOf(note,m_api->m_appr_mgr.e_note)) return;
	if(AfxMessageBox( APL_T("Удалить примечание?"),MB_YESNO|MB_ICONQUESTION)==IDNO) return;

	if(!m_api->m_appr_mgr.DeleteNote(note)) return;
	LoadData();
}

void CSelectNoteDlg::OnNotesRevoke()
{
	CaplInstance *note = (CaplInstance*)m_notes->m_tree.GetItemData(m_notes->m_tree.GetSelectedItem());
	if(!note) return; 
	if(!m_api->m_data.IsKindOf(note,m_api->m_appr_mgr.e_note)) return;

	CString buf;
	m_api->m_data.GetAttr(note,m_api->m_appr_mgr.a_note_date_revocation,buf);
	if(buf!=_T("")) {aplErrorMessage(APL_T("Примечание уже отменено!")); 		return;	}

	if(AfxMessageBox( APL_T("Отменить примечание?"),MB_YESNO|MB_ICONQUESTION)==IDNO) return;

	CaplInstance *p=0,*pers = m_api->m_appr_mgr.GetCurrentPerson();
	m_api->m_data.GetAttr(note,m_api->m_appr_mgr.a_note_author,p);
	if(p!=pers && !m_api->m_appr_mgr.IsAdmin())
	{
		aplErrorMessage(APL_T("Отменять чужие примечания может только администратор!"));
		return;
	}
	COleDateTime odt=COleDateTime::GetCurrentTime();
	aplDate2String(odt,buf);
	m_api->m_data.PutAttr(note,m_api->m_appr_mgr.a_note_date_revocation,buf);
	m_api->m_data.NET_SaveChanges();
	LoadData();
}

void CSelectNoteDlg::OnCopyNote() 
{
	long s, e;
	m_richedit.GetSel(s,e);
	if(s==e)
		m_richedit.SetSel(0, -1);
	m_richedit.Copy();
	m_richedit.SetSel(s, e);
}

void CSelectNoteDlg::OnAnsverNote() 
{
	CaplInstance *inst = (CaplInstance*)m_notes->m_tree.GetItemData(m_notes->m_tree.GetSelectedItem());
	if(inst==0) return;
	if(!m_api->m_data.IsKindOf(inst,m_api->m_appr_mgr.e_note)) return;
	if(m_api->m_appr_mgr.CreateNote(m_inst, inst))
		LoadData();
}

bool CSelectNoteDlg::LoadData()
{
	HTREEITEM parent;
	CMap<CaplInstance*, CaplInstance* , HTREEITEM, HTREEITEM> map;
	if(m_show_in_tree.GetCheck()!=0)
		m_notes->SetRedraw(FALSE);
	m_notes->m_tree.DeleteAllItems();
	aplExtent notes;
	CString descr, author, date, rev_date;
	m_api->m_appr_mgr.FindAssociatedNotes(m_inst, notes);
	CaplInstance *pers=0, *par = 0;
	COleDateTime time;
	notes.Unique = false;
	aplExtent skip;
	skip.Clear();
	m_richedit.SetRTF(_T(""));
	for(int i=0; i<notes.GetSize();i++)
	{
		m_api->m_data.GetAttr(notes.GetAt(i),m_api->m_appr_mgr.a_note_parent,par);
		parent = TVI_ROOT;
		if(par!=0)
		{
			//Поиск в карте
			parent = map[par];
			if(parent==0)
			{
				if(i<notes.GetSize()-1)
				{
					if(skip.Find(notes[i])>-1) continue;
					skip.Add(notes[i]);
					CaplInstance *tmp = notes[notes.GetSize()-1];
					notes.SetAt(notes.Size-1,notes[i]);
					notes.SetAt(i,tmp);
					i--; 
					continue;
				}
				else
					continue;
			}
		}
		m_api->m_data.GetAttr(notes.GetAt(i),m_api->m_appr_mgr.a_note_descr,descr);
		m_api->m_data.GetAttr(notes.GetAt(i),m_api->m_appr_mgr.a_note_author,pers);
		m_api->m_data.GetAttr(notes.GetAt(i),m_api->m_appr_mgr.a_note_date,date);

		aplString2Date(date,time);
		date = time.Format(DATE_FORMATE);
		if(descr==_T("")) descr = _T("???");

		m_api->m_data.GetAttr(notes.GetAt(i),m_api->m_appr_mgr.a_note_date_revocation,rev_date);
		if(rev_date!=_T("")) descr.Insert(0,APL_T("{Отменено}"));

		HTREEITEM ind = m_notes->m_tree.InsertItem(descr, parent);
		ASSERT(ind);
		m_notes->m_tree.SetItemData(ind,(DWORD)notes.GetAt(i));
		m_notes->m_tree.SetItemText(ind,1,date);
		m_api->m_appr_mgr.GetPersonName(pers,author);
		m_notes->m_tree.SetItemText(ind,2,author);
		map[notes[i]] = ind;

		int img=ICON_NOTE;
		m_api->m_data.GetAttr(notes.GetAt(i),m_api->m_prd_mgr.a_note_markup,descr);
		if(descr!=_T(""))img++;
		m_notes->m_tree.SetItemImage(ind,img,img);
	}
	//m_notes->SetRedraw(TRUE);
	if(m_show_in_tree.GetCheck()==0)
		AddNotes(m_inst);
	else
	{
		m_notes->SetRedraw(TRUE);
		m_notes->Invalidate();
	}
	m_notes->Expand(0);
	//m_notes->Expand(TVI_ROOT);
	return true;
}

BOOL CSelectNoteDlg::DestroyWindow() 
{	
	if(m_splitter) m_splitter->DestroyWindow();
	if(m_splitter) delete m_splitter;

	m_notes->m_tree.DeleteAllItems();
	
	return CaplResizableDialog::DestroyWindow();
}

void CSelectNoteDlg::OnSplitterMoved()
{
	ModifyAnchor(m_notes->m_hWnd);
	ModifyAnchor(m_richedit.m_hWnd);
	if(m_splitter) ModifyAnchor(m_splitter->m_hWnd);
}

void LoadContextMenuIcon();

void CSelectNoteDlg::OnContextMenu(CWnd* pWnd, CPoint point) 
{
	CRect r, rr;
	m_notes->GetWindowRect(r);
	m_richedit.GetWindowRect(rr);
	CMenu menu;
	CMenu *pPopup = 0;
	VERIFY(menu.LoadMenu(IDR_CONTEXT_MENU));
	LoadContextMenuIcon();
	CaplMenu::Install(this);
	pPopup = menu.GetSubMenu(7);
	ASSERT(pPopup);
	if(r.PtInRect(point) && m_notes->IsWindowVisible())
	{
		pPopup->DeleteMenu(2,MF_BYPOSITION);
		pPopup->DeleteMenu(2,MF_BYPOSITION);
		CPoint pt = point;
		m_notes->m_tree.ScreenToClient(&pt);

		HTREEITEM ht = m_notes->m_tree.HitTest(pt);
		CaplInstance *inst=0;
		if(ht!=0)
			inst = (CaplInstance*)m_notes->m_tree.GetItemData(ht);
		if(inst==0)
		{
			pPopup->EnableMenuItem(ID_NOTES_ANSVER, MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_NOTES_DELETE, MF_BYCOMMAND|MF_GRAYED);
		}
	}
	else if(rr.PtInRect(point))
	{
		pPopup->DeleteMenu(0,MF_BYPOSITION);
		pPopup->DeleteMenu(0,MF_BYPOSITION);
		pPopup->DeleteMenu(0,MF_BYPOSITION);
		pPopup->DeleteMenu(1,MF_BYPOSITION);
		pPopup->DeleteMenu(1,MF_BYPOSITION);
	}
	else return;
	pPopup->TrackPopupMenu(TPM_LEFTALIGN|TPM_RIGHTBUTTON,point.x,point.y,this);
}

void CSelectNoteDlg::AddNotes(CaplInstance *inst)
{
	aplExtent notes;
	m_api->m_appr_mgr.FindAssociatedNotes(inst, notes);
	int l=0, i=0;
	CaplInstance*par=NULL;
	CString rev_date,buf;
	m_richedit.SetRTF(_T(""));
	while(1)
	{
		l++;
		bool find = false;
		for(i=0; i<notes.GetSize();i++)
		{
			m_api->m_data.GetAttr(notes[i],m_api->m_appr_mgr.a_note_parent,par);
			if(par==0) {find = true;break;}
		}
		if(!find) return;
		CaplInstance *tmp = notes[i];
		CString level;
		level.Format(_T("%d"),l);
		long size;
		m_api->m_data.NET_GetBlobSize(tmp,m_api->m_appr_mgr.a_note_source, size);
		BYTE *c =  new BYTE[size];
		if(c==NULL)
		{
			AfxMessageBox( APL_T("Недостаточно памяти для загрузки примечания!"));
			return;
		}
		m_api->m_data.NET_LoadBlob2Memory(tmp,m_api->m_appr_mgr.a_note_source,c,size);
		CString rtf;
		rtf += (const char*)c;
		if(l>1) m_richedit.SetRTF(APL_SEPARATOR,APL_RC_SELECTION);
		CString date, author;
		m_api->m_data.GetAttr(tmp,m_api->m_appr_mgr.a_note_date, date);
		COleDateTime time;
		aplString2Date(date,time);
		date = time.Format(DATE_FORMATE);
		
		m_api->m_data.GetAttr(tmp ,m_api->m_appr_mgr.a_note_date_revocation,rev_date);
		if(rev_date!=_T(""))
		{
			date+=APL_T(")    Отменено! (");
			COleDateTime odt;
			aplString2Date(rev_date,odt);
			date+=odt.Format(DATE_FORMATE);
		}
		
		CaplInstance *pers;
		m_api->m_data.GetAttr(tmp,m_api->m_appr_mgr.a_note_author, pers);
		m_api->m_appr_mgr.GetPersonName(pers,author);
		CString fsize = _T("24");
		author = APL_AUTOR_DATE(level,author, date, fsize);
		m_richedit.SetRTF(author,APL_RC_SELECTION);
		m_richedit.SetRTF(rtf,APL_RC_SELECTION);
		delete c;

		if(!AddNotesRec(notes[i],notes,&m_richedit,m_api,level+_T("."))) return;
		notes.Remove(i);
	}
	m_richedit.Invalidate();
}

bool CSelectNoteDlg::GetChildNote(CaplInstance *parent, aplExtent &notes, aplExtent &childs, CaplAPI *api)
{
	childs.Clear();
	CaplInstance* par=0;
	for(int i=0; i<notes.GetSize();i++)
	{
		api->m_data.GetAttr(notes[i],api->m_appr_mgr.a_note_parent,par);
		if(par==parent) childs.Add(notes[i]);
	}
	return NULL;
}
bool CSelectNoteDlg::AddNotesRec(CaplInstance *note, aplExtent &notes, CaplRichEditCtrl *richedit, CaplAPI *api, CString level)
{
	if(note==0) return false;
	aplExtent childs;
	GetChildNote(note,notes,childs, api);
	for(int i=0; i<childs.Size;i++)
	{
		CaplInstance *tmp = childs[i];
		long size;
		api->m_data.NET_GetBlobSize(tmp,api->m_appr_mgr.a_note_source, size);
		BYTE *c =  new BYTE[size];
		if(c==NULL)
		{
			AfxMessageBox( APL_T("Недостаточно памяти для загрузки примечания!"));
			return false;
		}
		api->m_data.NET_LoadBlob2Memory(tmp,api->m_appr_mgr.a_note_source,c,size);
		CString rtf;
		rtf += (const char*)c;
		CString t, s;
		t.Format(_T("%s %i"),level,i+1);
		richedit->SetRTF(APL_SEPARATOR_LEVEL,APL_RC_SELECTION);
		CString date, author;
		api->m_data.GetAttr(tmp,api->m_appr_mgr.a_note_date, date);
		COleDateTime time;
		aplString2Date(date,time);
		date = time.Format(DATE_FORMATE);
		CaplInstance *pers;
		api->m_data.GetAttr(tmp,api->m_appr_mgr.a_note_author, pers);
		api->m_appr_mgr.GetPersonName(pers,author);
		CString fsize;
		fsize.Format(_T("%d"),24-level.GetLength());
		author = APL_AUTOR_DATE(t,author, date, fsize);
		richedit->SetRTF(author,APL_RC_SELECTION);
		richedit->SetRTF(rtf,APL_RC_SELECTION);
		delete c;
		AddNotesRec(tmp,notes,richedit,api,t+_T("."));
	}
	return true;
}

void CSelectNoteDlg::OnShowAll() 
{
	bool m_showall = m_show_in_tree.GetCheck()>0 ? true:false;
	if(m_showall)
	{
		CRect r1, r2;
		m_richedit.GetWindowRect(r1);
		m_notes->GetWindowRect(r2);
		ScreenToClient(r1);
		ScreenToClient(r2);
		r1.left = r2.left;
		m_notes->ShowWindow(SW_HIDE);
		m_splitter->ShowWindow(SW_HIDE);
		m_richedit.MoveWindow(r1);
		m_richedit.SetRTF(_T(""));
		AddNotes(m_inst);
		m_del.EnableWindow(FALSE);
		m_ansver.EnableWindow(FALSE);
	}
	else
	{
		CRect r1, r2;
		m_richedit.GetWindowRect(r1);
		m_splitter->GetWindowRect(r2);
		ScreenToClient(r1);
		ScreenToClient(r2);
		r1.left = r2.right;
		m_notes->ShowWindow(SW_SHOW);
		m_splitter->ShowWindow(SW_SHOW);
		m_richedit.MoveWindow(r1);
		CaplInstance *note = (CaplInstance*)m_notes->m_tree.GetItemData(m_notes->m_tree.GetSelectedItem());
		SetRTF(note);
		m_del.EnableWindow(TRUE);
		m_ansver.EnableWindow(TRUE);
	}
	ModifyAnchor(m_richedit.m_hWnd);
	m_show_in_tree.SetCheck(!m_showall);
}

bool CSelectNoteDlg::SetRTF(CaplRichEditCtrl *richedit, CaplInstance *inst, CaplAPI *api)
{
	if(api==0) return false;
	if(inst==0) return false;
	if(richedit==0) return false;
	if(!::IsWindow(richedit->m_hWnd)) return false;

	richedit->SetRTF(_T(""));
	aplExtent notes;
	api->m_appr_mgr.FindAssociatedNotes(inst, notes);
	int l=0, i=0;
	CaplInstance*par=NULL;
	while(1)
	{
		l++;
		bool find = false;
		for(i=0; i<notes.GetSize();i++)
		{
			api->m_data.GetAttr(notes[i],api->m_appr_mgr.a_note_parent,par);
			if(par==0) {find = true;break;}
		}
		if(!find) return true;
		CaplInstance *tmp = notes[i];
		CString level;
		level.Format(_T("%d"),l);
		long size;
		api->m_data.NET_GetBlobSize(tmp,api->m_appr_mgr.a_note_source, size);
		BYTE *c =  new BYTE[size];
		if(c==NULL)
		{
			AfxMessageBox( APL_T("Недостаточно памяти для загрузки примечания!"));
			return false;
		}
		api->m_data.NET_LoadBlob2Memory(tmp,api->m_appr_mgr.a_note_source,c,size);
		CString rtf;
		rtf += (const char*)c;
		if(l>1) richedit->SetRTF(APL_SEPARATOR,APL_RC_SELECTION);
		CString date, author;
		api->m_data.GetAttr(tmp,api->m_appr_mgr.a_note_date, date);
		COleDateTime time;
		aplString2Date(date,time);
		date = time.Format(DATE_FORMATE);
		CaplInstance *pers;
		api->m_data.GetAttr(tmp,api->m_appr_mgr.a_note_author, pers);
		api->m_appr_mgr.GetPersonName(pers,author);
		CString fsize = _T("24");
		author = APL_AUTOR_DATE(level,author, date, fsize);
		richedit->SetRTF(author,APL_RC_SELECTION);
		richedit->SetRTF(rtf,APL_RC_SELECTION);
		delete c;

		if(!AddNotesRec(notes[i],notes,richedit,api,level+_T("."))) return false;
		notes.Remove(i);
	}
	return true;
}

void CSelectNoteDlg::OnCancel() 
{
	m_api->m_data.NET_SaveChanges();
	
	
	CaplResizableDialog::OnCancel();
}


