#include "stdafx.h"
#include "aplMessageTreeItem.h"
#include "dictionary.h"

#include "PSMDoc.h"

#include "aplTopLevelItem.h"
#include "aplFolderTreeItem.h"
#include "TreeProductItem.h"
#include "aplDocTreeItem.h"
#include "aplTreeProcessItem.h"
#include "aplTreeTaskItem.h"
#include "aplChangeTreeItem.h"
#include "aplBPTreeItem.h"

#include "resource.h"
//статичесие переменные класса
int CaplMessageTreeItem::m_iNameFormate= APL_MESSAGE_NON_FORMATE;
int CaplMessageTreeItem::m_iShowPropertyEvent= APL_MESSAGE_NO_EVENT;
bool CaplMessageTreeItem::m_bShowName= true;
bool CaplMessageTreeItem::m_bShowDate= false;
bool CaplMessageTreeItem::m_bShowInListCtrl= true;

//методы класса
CaplMessageTreeItem::CaplMessageTreeItem(CTreeCtrl *tree, CPSMDoc *doc,
		CaplInstance *mess)
{
	m_type= APL_TREE_ITEM_MESSAGE;
	//Заменить на оригинал, когда смотрит отправитель рассылки
	m_message= mess;
	m_doc= doc;
	m_tree= tree;
	m_bLostMessage= false;
	m_bOriginalLetter= true;
	m_bCanReply= false;
	
	m_bShowContent= true;

	m_folder= 0;
	m_classifier=0;
	m_folderItem= NULL;
		
	if(doc!=0)
	{
		doc->m_items.Add(this);
//		ReplaceMesInstance(doc, &m_message);
		doc_data.GetAttr(m_message, doc->m_api.m_message_mgr.a_message_copies, m_copyMessages);
	}
}

bool CaplMessageTreeItem::ReplaceMesInstance(CPSMDoc* doc, CaplInstance** message)
{
	CaplInstance *inst,*person= doc->m_api.m_appr_mgr.GetCurrentPerson();

	if(person)
	{
		doc->m_api.m_data.GetAttr(*message, doc->m_api.m_message_mgr.a_message_sender, inst);
		if(inst==person)//смена при просмотре отправителем письма копии на оригинал
		{
			doc_data.GetAttr(*message, doc->m_api.m_message_mgr.a_message_copy, inst);
			if(inst)
			{
				*message= inst;//это оригинал
				if(-1==doc->m_incoming_messages.Find(*message) 
					&& -1==doc->m_send_or_dr_messages.Find(*message))
				{
					aplExtent ext1; ext1.Add(*message);
					doc->m_api.m_message_mgr.LoadMessageInfo(ext1);
				}
			}
		}
	}
	
	return true;
}

bool CaplMessageTreeItem::GetName(CString &name)
{	
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	CHECK_GET_NAME(m_message);

	CString buf1= _T("");
	CaplInstance *inst= NULL;
	if(m_bShowDate)
	{
		
	}
	if(m_bShowName)
	{
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_sender, inst);
		if(inst)
		{
			//m_doc->m_api.m_appr_mgr.GetPersonName(inst, name);
			m_doc->m_api.GetItemName(inst, name);
			name+=_T(" -> ");
		}
		else
		{
			name=_T("");
			m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_send_nick, buf1);
			if(!buf1.IsEmpty()) name.Format(_T("\"%s\" -> "), buf1);
			if(name.IsEmpty())	name=  APL_T("Система -> ");
		}
		
		if(m_copyMessages.GetSize()==0)
		{
			m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_rec_offisial, inst);
			if(!inst) m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_recipient, inst);
			
			//if(inst) m_doc->m_api.m_appr_mgr.GetPersonName(inst, buf1);
			if(inst) m_doc->m_api.GetItemName(inst, buf1);
			else{ m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_rec_nick, buf1); buf1= _T("\"")+buf1+_T("\"");}
			
			name+=buf1+_T(" : ");
		}
		else
			name+= APL_T("Рассылка : ");
	}
	name+= APL_T("Тема: ");
	m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_subject, buf1);
	name+=buf1;
	
	return true;
}

bool CaplMessageTreeItem::RefreshItem()  
{
	UINT ico=0,ico1=0;
	ico= ICON_MESSAGES+4;
	
	if(m_tree!=0)
	{
		if(m_message==NULL) return false;
		if(m_message->GetType()==NULL) return false;
		
		CString name, buf, str= _T("draft");
		CaplInstance* inst= NULL, *inst1= NULL;
		
		CaplLoadData ld(&m_doc->m_api.m_data,DEF_SOURCE);
		ld.AddQuery(0, m_message);
		ld.AddQuery(_T('d'), 0, 0, m_doc->m_api.m_message_mgr.a_message_status, true);
		ld.AddQuery(_T('d'), 0, 0, m_doc->m_api.m_message_mgr.a_message_prev_message, true);
		ld.AddQuery(_T('d'), 0, 0, m_doc->m_api.m_message_mgr.a_message_forward, true);
		ld.LoadEx();

		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_status, buf);
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_forward, inst);
		
		if(inst)
		{
//			m_doc->m_api.m_message_mgr.LoadMessageInfo(inst);
//			ld.ClearQuery();
//			ld.AddQuery(0, inst);
//			ld.AddQuery(_T('d'), 0, 0, m_doc->m_api.m_message_mgr.a_message_status, true);
//			ld.AddQuery(_T('d'), 0, 0, m_doc->m_api.m_message_mgr.a_message_forward, true);
//			ld.LoadEx();
//			
//			m_doc_data.GetAttr(inst, m_doc->m_api.m_message_mgr.a_message_status, str);		
//			m_doc_data.GetAttr(inst, m_doc->m_api.m_message_mgr.a_message_forward, inst1);		
		}

		if(!m_bLostMessage)
		{
			if(buf==_T("draft")){/*та же иконка*/ ico-=0;}
			else if(m_copyMessages.GetSize()==0)
			{
				if(buf==_T("readed"))
				{
					ico+=1;
					if(inst) ico+=2;
				}
				else if(buf==_T("replyed")) 
				{
					ico+=2;
					if(inst) ico+=2;
				}
			}
			else
			{
				ico+=6;
			}
		}
		else
		{
			ico+=5;
		}

		GetName(name);
		
		SetItemImage(ico, IDX_IL_TREE_ITEM);
		m_tree->SetItemText(m_item, name);
		
		Sort();
		m_tree->RedrawWindow();
	}
	return true;
}

void CaplMessageTreeItem::GetAccessedInstances(aplExtent &ext)
{
	ext.Clear();
	if(m_message!=0){if(m_message->GetType()!=0)ext.Add(m_message);}
}

bool CaplMessageTreeItem::TrackPopupMenu(CWnd *wnd, CPoint &point, UINT view_mode)
{
	CMenu menu;  gSetPsmResourceHandle();
	VERIFY(menu.LoadMenu(IDR_TREE_CONTEXT_MENU));
// 	VERIFY(menu.LoadToolBar(IDR_MENU_ICONS));
	CaplMenu::Install(wnd); // 	VERIFY(CaplMenu::Install(wnd, ePopupMenu ));
    CMenu* pPopup = menu.GetSubMenu(INDEX_MESSAGE_MENU);
    ASSERT(pPopup != NULL);
	if(pPopup==0) return false;
	
	UpdateMenu((CMenu**)&pPopup, view_mode);
	
	CaplInstance* inst;
	CaplInstance* sender, *recipient, *recipient_off, *person;

	if(m_message==0 || m_message->GetType()==0)
	{
/*		pPopup->EnableMenuItem(ID_MESSAGE_CREATE, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_MESSAGE_READ, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_MESSAGE_REPLY, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_MESSAGE_FORWARD, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_MESSAGE_SEND, MF_BYCOMMAND | MF_GRAYED);
		pPopup->EnableMenuItem(ID_DELETE, MF_BYCOMMAND | MF_GRAYED);*/

		return false;
	}
	else
	{
		if (m_message->GetAccessmode() != aplOWN)
			pPopup->EnableMenuItem(ID_DELETE, MF_BYCOMMAND | MF_GRAYED);
		CString buf;
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_status, buf);
		if(buf!=_T("draft"))
			pPopup->EnableMenuItem(ID_MESSAGE_SEND, MF_BYCOMMAND | MF_GRAYED);
		else
			pPopup->EnableMenuItem(ID_MESSAGE_FORWARD, MF_BYCOMMAND | MF_GRAYED);

		person=  m_doc->m_api.m_appr_mgr.GetCurrentPerson();
		
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_sender, sender);
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_recipient, recipient);
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_rec_offisial, recipient_off);

		if(person==sender || !sender)
			pPopup->EnableMenuItem(ID_MESSAGE_REPLY, MF_BYCOMMAND | MF_GRAYED);

		bool add_rec = person!=recipient && recipient!=0 || person!=recipient_off && recipient_off!=0;
		bool add_sen = person!=sender && sender!=0;
		if(add_rec || add_sen)
		{
			pPopup->InsertMenu(4,MF_BYPOSITION|MF_SEPARATOR,0,_T(""));
			if(add_rec)pPopup->InsertMenu(5,MF_BYPOSITION|MF_STRING,ID_ADD2ADDRESS_BOOK_RECIPI,S::message_add2address_recipient());
			if(add_sen)pPopup->InsertMenu(5,MF_BYPOSITION|MF_STRING,ID_ADD2ADDRESS_BOOK_SENDER,S::message_add2address_sender());
		}

		if(person!=sender && person!=recipient)
		{
			if(m_bCanReply==false)
				pPopup->EnableMenuItem(ID_MESSAGE_REPLY, MF_BYCOMMAND | MF_GRAYED);
			pPopup->EnableMenuItem(ID_MESSAGE_FORWARD, MF_BYCOMMAND | MF_GRAYED);
			pPopup->EnableMenuItem(ID_MESSAGE_SEND, MF_BYCOMMAND | MF_GRAYED);
			if(!m_doc->m_api.m_data.IsAdmin())
				pPopup->EnableMenuItem(ID_DELETE, MF_BYCOMMAND | MF_GRAYED);
			pPopup->EnableMenuItem(ID_REMOVE_FROM_FOLDER, MF_BYCOMMAND | MF_GRAYED);
		}
		if(m_folder)
		{
			if(person==sender)
			{
				m_doc_data.GetAttr(m_message, 
					m_doc->m_api.m_message_mgr.a_message_sender_folder, inst);
				if(inst!=m_folder)
					pPopup->EnableMenuItem(ID_REMOVE_FROM_FOLDER, MF_BYCOMMAND | MF_GRAYED);			
			}
			if(person==recipient)
			{
				m_doc_data.GetAttr(m_message, 
					m_doc->m_api.m_message_mgr.a_message_recipient_folder, inst);
				if(inst!=m_folder)
					pPopup->EnableMenuItem(ID_REMOVE_FROM_FOLDER, MF_BYCOMMAND | MF_GRAYED);			
			}
		}
		else
		{
			pPopup->EnableMenuItem(ID_REMOVE_FROM_FOLDER, MF_BYCOMMAND | MF_GRAYED);			
		}
		if(m_classifier==0){pPopup->EnableMenuItem(ID_REMOVE_FROM_CLASSIFIER, MF_BYCOMMAND | MF_GRAYED);}

		if(m_copyMessages.GetSize()==0)
		{
			pPopup->EnableMenuItem(ID_DISP_MESSAGES_STATE, MF_BYCOMMAND | MF_GRAYED);						
		}
	}


	BOOL res = pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD,
						point.x, point.y, wnd);

	bool bCheck= true;
	CString buf;
	aplExtent ext;

	switch (res)
	{
		case ID_NEW_MESSAGE_CREATE:
			CreateMessage(m_doc, NULL, ext);
		break;
		case ID_SHOW_PROPERTIES:
		case ID_MESSAGE_READ:
			ShowProperties();
			break;
		case ID_MESSAGE_REPLY:
			if(m_doc->m_api.m_message_mgr.Reply(this->m_message))
			{
				m_iShowPropertyEvent= APL_MESSAGE_ADD_EVENT;
				RefreshAllMessages(m_doc);
			}
			break;
		case ID_MESSAGE_FORWARD:
			if(m_doc->m_api.m_message_mgr.Forward(this->m_message))
			{
				m_iShowPropertyEvent= APL_MESSAGE_ADD_EVENT;
				RefreshAllMessages(m_doc);
			}
			break;
		case ID_MESSAGE_SEND:			
			if(3==m_doc->m_api.m_message_mgr.SendDraftMessage(m_message))
			{
				m_iShowPropertyEvent= APL_MESSAGE_SEND_EVENT;
				RefreshAllMessages(m_doc);				
			}
			else
			{
				RefreshItem();				
			}
			break;
		case ID_DELETE:
			if(AfxMessageBox( APL_T("Вы действительно хотите удалить сообщение?"),MB_YESNO)==IDYES)
			{
				if(m_doc->m_api.m_message_mgr.DeleteMessage(this->m_message))
				{
					m_iShowPropertyEvent= APL_MESSAGE_DELETE_EVENT;
					RefreshAllMessages(m_doc);
				}
			}
			break;
		case ID_REMOVE_FROM_FOLDER:
			{
				inst= NULL;
				if(person==sender)
				{
					m_doc_data.PutAttr(m_message, 
						m_doc->m_api.m_message_mgr.a_message_sender_folder, inst);
					m_doc_data.GetAttr(m_message, 
						m_doc->m_api.m_message_mgr.a_message_recipient_folder, inst);
					if(!inst)
					{
						if(m_doc->m_api.m_folder_mgr.RemoveFromFolder(m_folder, m_message))
							m_folderItem->m_contents.Remove(m_folderItem->m_contents.Find(m_message));
					}
				}
				if(person==recipient)
				{
					m_doc_data.PutAttr(m_message, 
						m_doc->m_api.m_message_mgr.a_message_recipient_folder, inst);
					m_doc_data.GetAttr(m_message, 
						m_doc->m_api.m_message_mgr.a_message_sender_folder, inst);
					if(!inst)
					{
						m_doc->m_api.m_folder_mgr.RemoveFromFolder(m_folder, m_message);
						m_folderItem->m_contents.Remove(m_folderItem->m_contents.Find(m_message));
					}
				}
				
				m_folderItem->ShowContents();

				m_doc_data.NET_SaveChanges();
				m_iShowPropertyEvent= APL_MESSAGE_ADD_EVENT;
				RefreshAllMessages(m_doc);				
				
				m_doc->m_items.Remove(m_doc->m_items.Find(this));
			}
			break;
		case ID_REMOVE_FROM_CLASSIFIER:
			if(m_classifier!=0)
			{
				if(m_doc->m_api.m_classifier_mgr.DeleteClassifierAssociation(m_message,m_classifier))
					m_doc->m_items.Remove(m_doc->m_items.Find(this));
			}
			break;
		case ID_SHOW_MESSAGE_ITEMS:
			ShowItems();
			break;
		case ID_SHOW_MES_NEXT:
			{
				CaplAttrValue val[3];
				aplExtent ext;
				
				val[0].value.Set(m_message);
				val[0].attr= m_doc->m_api.m_message_mgr.a_message_prev_message;

				m_doc_data.NET_FindInstancesWithAttrValues(m_doc->m_api.m_message_mgr.e_message, 1, 
					&val[0], ext, false);
				

//				if(person==sender)
				{
					//это чувак, возможно, смотрит рассылку
					aplExtent copies;
					for(int j= 0; j<m_copyMessages.GetSize(); j++)
					{
						val[0].value.Set(m_copyMessages[j]);
						m_doc_data.NET_FindInstancesWithAttrValues(m_doc->m_api.m_message_mgr.e_message, 1, 
							&val[0], copies, false);
						for(int n= 0; n<copies.GetSize(); n++)
							ext.Add(copies[n]);
					}
				}
				
				bool bSave= false;

				CString sDate;	
				COleDateTime odt;
				m_doc->m_api.m_data.NET_GetServerDateTime(odt);
				aplDate2String(odt, sDate);	
				
				for(int i= 0; i<ext.GetSize(); i++)
				{
					if(-1==m_refMessages.Find(ext[i]))
					{
						m_doc->m_api.m_message_mgr.LoadMessageInfo(ext[i]);
						CaplInstance* rec= NULL;
						m_doc_data.GetAttr(ext[i], m_doc->m_api.m_message_mgr.a_message_recipient, rec);
						if(rec==person)
						{
							m_doc_data.PutAttr(ext[i], m_doc->m_api.m_message_mgr.a_message_date_received, sDate);
							bSave= true;							
						}
						m_iNameFormate= APL_MESSAGE_INCOMING_FORMATE;
						
						CaplMessageTreeItem *message_item=
							new CaplMessageTreeItem(m_doc->m_user_incoming_folder->m_tree, 
							m_doc, ext[i]);
						message_item->CreateTreeItem(m_item);
						
						m_refMessages.Add(ext[i]);
					}
				}
				
				if(bSave) m_doc_data.NET_SaveChanges();

				m_bShowContent= false;
				MyExpand();
				m_bShowContent= true;
				m_tree->RedrawWindow();
			}
			break;
		case ID_DISP_MESSAGES_STATE:
			m_doc->m_api.m_message_mgr.ShowDispMessageState(m_message);
			break;
		case ID_ADD2ADDRESS_BOOK_RECIPI:
			// адресная книга
			if(recipient!=0)
			{
				if(m_doc->m_api.m_message_mgr.Add2AddressBook(recipient))
				{
					AfxMessageBox(S::message_add2address_recipient_performed());
				}
			}
			else if(recipient_off!=0)
			{
				if(m_doc->m_api.m_message_mgr.Add2AddressBook(recipient_off))
				{
					AfxMessageBox(S::message_add2address_recipient_performed());
				}
			}
			break;
		case ID_ADD2ADDRESS_BOOK_SENDER:
			// адресная книга
			if(m_doc->m_api.m_message_mgr.Add2AddressBook(sender))
			{
				AfxMessageBox(S::message_add2address_sender_performed());
			}
			break;

		case ID_SAVE_TO_FILE:
			{
				CFileDialog save_dialog(FALSE, _T("eml"), _T(""),OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
					APL_T("Файлы сообщений (*.eml)|*.eml|Все файлы (*.*)|*.*||"));
				if (save_dialog.DoModal() == IDOK)
				{  
					if(m_doc->m_api.m_message_mgr.SaveMessageToEml(m_message,save_dialog.GetPathName()))
						AfxMessageBox(APL_T("Готово!"),MB_OK|MB_ICONINFORMATION);
					else AfxMessageBox(APL_T("Ошибка при сохранении!"),MB_OK|MB_ICONSTOP); 
				}
			}
			break;


		default: PrepareContextMenu(res);
			break;
	}
	return true;
}

BOOL CaplMessageTreeItem::ShowToolBarButton(CCmdUI* pCmdUI)
{
	switch(pCmdUI->m_nID)
	{
/*	case ID_SHOW_ALL_DOCS:
	case ID_SHOW_ALL_CHARACTERISTIC:
	case ID_SHOW_ALL_APPROVAL:
	case ID_PRODUCT_SHOW_ALL_ZAGOTOV:
	case ID_SHOW_ALL_LOT:
	case ID_SHOW_ALL_PRD_INST:
	case ID_CREATE_APPROVAL:
	case ID_SHOW_ALL_VERSION:
	case ID_CREATE_PRODUCT:
	case ID_CREATE_CHARACTERISTIC:
	case ID_CREATE_DOC:*/
	case ID_SHOW_NOTES:
	case ID_CREATE_NOTE:
		pCmdUI->Enable(TRUE); return TRUE; break;
	}
	return FALSE;
}

void CaplMessageTreeItem::ShowCmd(long cmd)
{
	
}

bool CaplMessageTreeItem::Expand(UINT action)
{
	bool bRes= false;
	if(action==2)
	{
		if(m_expanded) return true;
		if(m_hasSubItem) Expand(1);
		if(m_fictive_item!=0)
		{
			m_tree->DeleteItem(m_fictive_item);
			m_fictive_item=0;
		}
		
		if(m_bShowContent)
		{
			ShowMessageHistory();
			ShowItems();
			Sort();
		}
		
		m_expanded= true;
	}
	else if(action==1)
	{
		m_bShowInListCtrl= false;
		CollapseItem();
		m_bShowInListCtrl= true;
		
		m_refMessages.Clear();
		m_items.Clear();
	}	
	return bRes;
}

bool CaplMessageTreeItem::CreateTreeItem(HTREEITEM parent_item)
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	
	if(m_message==NULL) return false;
	if(m_message->GetType()==NULL) return false;

	bool bRes= false;
	UINT ico= ICON_MESSAGES+4;	
	CString buf, str= _T("draft");
	CaplInstance* inst= NULL, *inst1= NULL;

	m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_status, buf);
	m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_forward, inst);
	
	if(inst)
	{
//		CaplLoadData ld(&m_doc->m_api.m_data,DEF_SOURCE);
//	i=	ld.AddQuery(inst);
//		ld.AddQuery(_T('d'), i, 0, m_doc->m_api.m_message_mgr.a_message_status, true);
//		ld.AddQuery(_T('d'), i, 0, m_doc->m_api.m_message_mgr.a_message_forward, true);
//		ld.LoadEx();
//		
//		m_doc_data.GetAttr(inst, m_doc->m_api.m_message_mgr.a_message_status, str);		
//		m_doc_data.GetAttr(inst, m_doc->m_api.m_message_mgr.a_message_forward, inst1);		
	}

	if(!m_bLostMessage)
	{
		if(buf==_T("draft")){/*та же иконка*/ ico-=0;}
		else if(m_copyMessages.GetSize()==0)
		{
			if(buf==_T("readed"))
			{
				ico+=1;
				if(inst) ico+=2;
			}
			else if(buf==_T("replyed")) 
			{
				ico+=2;
				if(inst) ico+=2;
			}
		}
		else
		{
			ico+=6;
		}
	}
	else
	{
		ico+=5;
	}

	buf=_T("");
	GetName(buf);
	
	InsetItem(buf,ico,parent_item);
	SetItemImage(ico, IDX_IL_TREE_ITEM);
	m_fictive_item=m_tree->InsertItem(_T("fictive"), 0, 0, m_item);

	m_expanded=false;
	bRes= true;

	return bRes;
}

bool CaplMessageTreeItem::ShowInListCtrl(CListCtrl *list)
{
	if(!m_bShowInListCtrl) return false;
	bool bRes= false;

	if(list==0) return bRes;
	else list->DeleteAllItems();
	
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	
	if(m_message==NULL || m_message->GetType()==NULL)
	{
		list->InsertItem(0,  APL_T("Сообщение удалено"));
		return false;
	}
			
	int i, k, n= -1;
	CString buf, buf1;
	CaplInstance *inst, *inst1;
	CaplAggr aggr0;
	COleDateTime odt;
	if(m_message && m_message->GetAccessmode()<aplNO && (0!=m_message->GetType()))
	{
		m_doc->m_api.m_message_mgr.LoadMessageInfo(m_message);

		i= list->InsertItem(++n,  APL_T("Тема:"));
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_subject, buf);
		list->SetItemText(i, 1, buf);
		
		i=list->InsertItem(++n,  APL_T("Важность:"));
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_priority, k);
		switch (k)
		{
			case 0: buf=  APL_T("Высокая");
				break;
			case 1: buf=  APL_T("Обычная");
				break;
			case 2: buf=  APL_T("Низкая");
				break;
		}
		list->SetItemText(i, 1, buf);		
		
		list->InsertItem(++n, _T(""));
		
		i= list->InsertItem(++n,  APL_T("Отправитель:"));
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_sender, inst);
		buf= _T("");
		list->SetItemText(i, 1, GetMessageSend(m_doc, m_message));		
		
		CaplInstance *msg_parent;
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_copy, msg_parent);
		aplExtent ext_copyMessages;

		if(msg_parent) m_doc_data.GetAttr(msg_parent, m_doc->m_api.m_message_mgr.a_message_copies, ext_copyMessages);
		else m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_copies, ext_copyMessages);

		if(ext_copyMessages.GetSize()==0)
		{
			i=list->InsertItem(++n,  APL_T("Получатель:"));
			m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_rec_offisial, inst);
			if(inst)
			{
				//m_doc->m_api.m_appr_mgr.GetPersonName(inst, buf);
				m_doc->m_api.GetItemName(inst, buf);
				list->SetItemText(i, 1, buf);
				i= list->InsertItem(++n,  APL_T("Получил:"));
			}
			m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_recipient, inst1);
			if(inst1)
			{
				//m_doc->m_api.m_appr_mgr.GetPersonName(inst1, buf);
				m_doc->m_api.GetItemName(inst1, buf);
				list->SetItemText(i, 1, buf);
			}
			if(!inst && !inst1)
			{
				m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_rec_nick, buf1);			
				if(!buf1.IsEmpty()) buf.Format(_T("e-mail \"%s\""), buf1);				
				list->SetItemText(i, 1, buf);
			}
		}
		else//рассылка
		{
			buf= _T("");
			i=list->InsertItem(++n,  APL_T("Получатели:"));
			list->SetItemText(i, 1, GetMessageRecip(m_doc, m_message));
		}

		i=list->InsertItem(++n, _T(""));

		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_date_send, buf);
		if(!buf.IsEmpty())
		{
			i=list->InsertItem(++n,  APL_T("Отправлено:"));
			aplString2Date(buf, odt);	
			buf= odt.Format(_T("%d.%m.%Y  %H:%M"));
			list->SetItemText(i,1,buf);
		}

		if(ext_copyMessages.GetSize()==0)
		{
			m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_date_received, buf);
			if(!buf.IsEmpty())
			{
				aplString2Date(buf, odt);	
				buf= odt.Format(_T("%d.%m.%Y  %H:%M"));
			} else  buf=APL_T("не получено");
			
		i=list->InsertItem(++n,  APL_T("Получено:"));
			list->SetItemText(i, 1, buf);
		}
		else
		{
			i=list->InsertItem(++n,  _T(""));
			i=list->InsertItem(++n,  APL_T("Получено:"));
			CString sName;
			for(int i1= 0; i1<ext_copyMessages.GetSize(); i1++)
			{
				CaplInstance *person= NULL;
				m_doc_data.GetAttr(ext_copyMessages[i1], m_doc->m_api.m_message_mgr.a_message_rec_offisial, person);
				if(!person) m_doc_data.GetAttr(ext_copyMessages[i1], m_doc->m_api.m_message_mgr.a_message_recipient, person);
				//if(person){doc->m_api.m_appr_mgr.GetPersonName(person, str); sName+=str;}
				if(person)m_doc->m_api.GetItemName(person, sName); 
				else sName=_T("?");

				m_doc_data.GetAttr(ext_copyMessages[i1], m_doc->m_api.m_message_mgr.a_message_date_received, buf);
				if(buf==_T("")) buf=APL_T("не получено");
				else {
					aplString2Date(buf, odt);	
					buf= odt.Format(_T("%d.%m.%Y  %H:%M"));
				} 
				i=list->InsertItem(++n,  sName);
				list->SetItemText(i, 1, buf);
			}
		}
	}

	aplExtent ext;
	CStringArray comment;
	if(m_message!=0){ comment.Add(_T("m_message")); ext.Add(m_message);}
	if(m_folder!=0){ comment.Add(_T("m_folder")); ext.Add(m_folder);}
	if(m_classifier!=0){
		CaplInstance* classif_ref;
		m_doc->m_api.m_classifier_mgr.TestClassifierAssociation(m_message,m_classifier,&classif_ref);
		if(classif_ref!=0){
			comment.Add(_T("classifier association"));
			ext.Add(classif_ref);
		}
		comment.Add(_T("m_classifier"));
		ext.Add(m_classifier);
	}
	ShowInstanceInfoInListCtrl(ext,list,&comment);
	return bRes;
}

void CaplMessageTreeItem::LoadProperties()
{
	_APL_TREE_ITEM_CHEK_PARAM_VOID
	
	if(m_message)
	{
//		m_doc->m_api.m_message_mgr.LoadMessageInfo(m_message);
	}
}

void CaplMessageTreeItem::ShowProperties()
{
	_APL_TREE_ITEM_CHEK_PARAM_VOID
	
	if(m_message && m_message->GetType())
	{
		int iRes= m_doc->m_api.m_message_mgr.ShowMessageProperty(m_message);
		
		switch(iRes)
		{
			case 0: //
				CaplInstance *inst1, *inst2, *person;

				m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_sender, inst1);
				m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_recipient, inst2);
				
				person= m_doc->m_api.m_appr_mgr.GetCurrentPerson();
				if(!person) return;
				
				if(person==inst1)
					m_iNameFormate= APL_MESSAGE_SENDED_FORMATE;
				else
					m_iNameFormate= APL_MESSAGE_INCOMING_FORMATE;		
				
				m_tree->SetRedraw(FALSE);
				RefreshItem();
				Expand(1);
				ShowMessageHistory();
				ShowItems();
				m_tree->SetRedraw(TRUE);
				
				break;
			case 1: m_iShowPropertyEvent= APL_MESSAGE_DELETE_EVENT;
				break;
			case 2: m_iShowPropertyEvent= APL_MESSAGE_ADD_EVENT;
				break;
			case 3: m_iShowPropertyEvent= APL_MESSAGE_SEND_EVENT;
				break;
		}

		if(!m_message->IsDeleted()) m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_copies, m_copyMessages);
		
		RefreshItem();
		RefreshAllMessages(m_doc);
		m_iNameFormate= APL_MESSAGE_NON_FORMATE;
	}
}

bool CaplMessageTreeItem::CreateMessage(CPSMDoc *doc, CaplInstance* recipient, aplExtent &ext)
{
	if(!doc) return false;

	if(recipient && 
		!doc->m_api.m_data.IsKindOf(recipient, doc->m_api.m_appr_mgr.e_person) &&
		!doc->m_api.m_data.IsKindOf(recipient, doc->m_api.m_appr_mgr.e_official))
	{
		return false;
	}

	CaplInstance *mes= doc->m_api.m_message_mgr.CreateMessage(NULL, recipient, 0, 0, ext);
	if(mes)
	{
		m_iNameFormate= APL_MESSAGE_SENDED_FORMATE;
		
		CString sSt;
		doc_data.GetAttr(mes, doc->m_api.m_message_mgr.a_message_status, sSt);
		if(sSt==_T("draft") && doc->m_user_drafted_folder)
		{
			CaplMessageTreeItem *message_item=
				new CaplMessageTreeItem(doc->m_user_drafted_folder->m_tree, doc, mes);
			message_item->m_tree->SetRedraw(FALSE);
			message_item->CreateTreeItem(doc->m_user_drafted_folder->m_item);
			doc->m_user_sended_folder->Sort();
			message_item->m_tree->SetRedraw(TRUE);
			doc->m_send_or_dr_messages.Add(mes);
		}
		else if(sSt==_T("sendet") && doc->m_user_sended_folder)
		{
			CaplMessageTreeItem *message_item=
				new CaplMessageTreeItem(doc->m_user_sended_folder->m_tree, doc, mes);
			doc->m_user_sended_folder->m_tree->SetRedraw(FALSE);
			message_item->CreateTreeItem(doc->m_user_sended_folder->m_item);
			doc->m_user_sended_folder->Sort();
			doc->m_user_sended_folder->m_tree->SetRedraw(TRUE);
			doc->m_send_or_dr_messages.Add(mes);
		}

		m_iNameFormate= APL_MESSAGE_NON_FORMATE;
	}

	return true;
}

bool CaplMessageTreeItem::ShowAllMessages(CPSMDoc *doc)
{	
	bool bRes= false;
	CString sName;
	
	if(!doc) return bRes;
	if(!doc_data.IsConnected()) return bRes;
	
	if(!doc->m_user_incoming_folder)
	{
		for(int i= 0; i<doc->m_items.GetSize(); i++)
		{
			doc->m_items[i]->GetName(sName);
			if(!sName.Compare( APL_T("Почта")))
			{
				doc->m_items[i]->MyExpand();
				break;
			}
		}
	}
	
	if(!doc->m_user_incoming_folder) return bRes;
	if(!doc->m_user_sended_folder) return bRes;
	if(!doc->m_user_drafted_folder) return bRes;

	doc->m_user_incoming_folder->Expand(1);
	doc->m_user_incoming_folder->MyExpand();
//	doc->m_user_sended_folder->Expand(1);
//	doc->m_user_sended_folder->MyExpand();
//	doc->m_user_drafted_folder->Expand(1);
//	doc->m_user_drafted_folder->MyExpand();

	//потестить и стереть все, что ниже...
	return true;

	aplExtent ext;

	bool bIsNotFound= true;
	bool bIsNewMessageFound= false;
	bool bSt;
	
	CaplInstance* inst;
	CaplInstance* person=doc->m_api.m_appr_mgr.GetCurrentPerson();
	if(!person) return false;

	doc->m_api.m_message_mgr.GetAllMessages(ext);
	
/*	CaplAttrValue val[2];
	aplExtent ext1;
	
	ent1= data->GetEntityBN(S::apl_message);
	val[0].value.Set(person);
	val[0].attr= data->GetAttrDefinitionBN(S::apl_message, S::sender);
	val[1].value.Set(_T("draft"));
	val[1].attr= data->GetAttrDefinitionBN(S::apl_message, S::status);

	data->NET_FindInstancesWithAttrValues(ent1, 2, &val[0], ext, false);*/
	
	bool bMod= false;

	CString sDate;	
	COleDateTime odt;
	doc->m_api.m_data.NET_GetServerDateTime(odt);
	aplDate2String(odt, sDate);	

	for(int i= 0; i<ext.Size; i++)
	{
		CString buf;
		doc_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_status, buf);
		doc_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_recipient, inst);
		doc_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_recipient_kill, bSt);

		//получатель сообщения
		if(inst==person && !bSt && buf!=_T("draft"))
		{
			//показываем все сообщения, если они не в другой папке и не удалены
			if(-1==doc->m_incoming_messages.Find(ext[i]))
			{
				bIsNotFound= false;
				doc_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_date_received, buf);
				if(buf.IsEmpty() || buf== _T(" "))
				{
					bIsNewMessageFound= true;
					doc_data.PutAttr(ext[i], doc->m_api.m_message_mgr.a_message_date_received, sDate);
				}

				m_iNameFormate= APL_MESSAGE_INCOMING_FORMATE;
				
				if(doc->m_user_incoming_folder)
				{
					CaplMessageTreeItem *message_item=
						new CaplMessageTreeItem(doc->m_user_incoming_folder->m_tree, 
						doc, ext[i]);
					message_item->CreateTreeItem(doc->m_user_incoming_folder->m_item);
					doc->m_incoming_messages.Add(ext[i]);
				}
			}
		}

		doc_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_sender, inst);
		doc_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_sender_kill, bSt);

		if(inst==person && !bSt)
		{
			if(-1==doc->m_send_or_dr_messages.Find(ext[i]))
			{
				bIsNotFound= false;
				
				m_iNameFormate= APL_MESSAGE_SENDED_FORMATE;
				CaplInstance* inst= NULL;
				doc_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_copy, inst);
				
				if(!inst)
				{
					if(buf==_T("draft"))
					{
						if(doc->m_user_drafted_folder)
						{
							CaplMessageTreeItem *message_item=
								new CaplMessageTreeItem(doc->m_user_drafted_folder->m_tree, doc, ext[i]);
							message_item->CreateTreeItem(doc->m_user_drafted_folder->m_item);
						}
					}
					else
					{
						if(doc->m_user_sended_folder)
						{
							CaplMessageTreeItem *message_item=
								new CaplMessageTreeItem(doc->m_user_sended_folder->m_tree, doc, ext[i]);
							message_item->CreateTreeItem(doc->m_user_sended_folder->m_item);
						}
					}

					doc->m_send_or_dr_messages.Add(ext[i]);
				}
			}
		}
	}


#ifdef _DEBUG
//	if(bIsNotFound) AfxMessageBox(APL_T("Новые сообщения не найдены!"));
#endif
	
	if(bIsNewMessageFound)
	{
		doc_data.NET_SaveChanges();
		
		//MessageBox(NULL, APL_T("Получены новые сообщения!"), APL_T("Новые сообщения"), MB_OK|MB_ICONINFORMATION);
		AfxMessageBox( APL_T("Получены новые сообщения!"), MB_OK|MB_ICONINFORMATION);
	}

	m_iNameFormate= APL_MESSAGE_NON_FORMATE;
	return bRes;
}

void CaplMessageTreeItem::ShowMessageHistory()
{
	_APL_TREE_ITEM_CHEK_PARAM_VOID

	if(m_message==NULL) return;
	if(m_message->GetType()==NULL) return;
	
	if(m_expanded) return;

	CaplInstance *prev_mes;
	m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_prev_message, prev_mes);
	if(!prev_mes) return;
	CaplInstance *forw_mes;

//	m_doc->m_api.m_message_mgr.LoadMessageInfo(prev_mes);
	m_doc_data.GetAttr(prev_mes, m_doc->m_api.m_message_mgr.a_message_forward, forw_mes);

	if(prev_mes!=forw_mes)
	{
/*		m_iNameFormate= APL_MESSAGE_SENDED_FORMATE;*/
		CaplInstance* inst;
		CaplInstance* person=m_doc->m_api.m_appr_mgr.GetCurrentPerson();
		if(!person) return;
		
		bool bIsShow= true,
			bSt= false;
		
		m_doc->m_api.m_message_mgr.LoadMessageInfo(prev_mes);
		
		m_doc_data.GetAttr(prev_mes, m_doc->m_api.m_message_mgr.a_message_sender, inst);
		m_doc_data.GetAttr(prev_mes, m_doc->m_api.m_message_mgr.a_message_sender_kill, bSt);
//		if(inst==person && !bSt) bIsShow= true;/*!!!*/
		if(inst==person)
		{ 
			if(bSt) bIsShow= false;/*!!!*/

			CaplInstance* copy= NULL;
			m_doc_data.GetAttr(prev_mes, m_doc->m_api.m_message_mgr.a_message_copy, copy);
			if(copy)
			{
				prev_mes= copy;
				m_doc->m_api.m_message_mgr.LoadMessageInfo(prev_mes);
			}
		}
		
		m_doc_data.GetAttr(prev_mes, m_doc->m_api.m_message_mgr.a_message_recipient, inst);
		m_doc_data.GetAttr(prev_mes, m_doc->m_api.m_message_mgr.a_message_recipient_kill, bSt);
//		if(inst==person && !bSt) bIsShow= true;/*!!!*/
		if(inst==person && bSt) bIsShow= false;/*!!!*/

		if(bIsShow)
		{
			CaplMessageTreeItem *message_item=
				new CaplMessageTreeItem(this->m_tree, m_doc, prev_mes);
			m_iNameFormate= APL_MESSAGE_INCOMING_FORMATE;
			
			if(forw_mes==m_message)
				message_item->m_bCanReply= true;

			message_item->CreateTreeItem(this->m_item);
			m_expanded= true;
		}
	}
}


void CaplMessageTreeItem::RefreshAllMessages(CPSMDoc *doc)
{
	if(!doc) return;

	int i;
	aplExtent ext;
	CString buf;
	CaplInstance* inst;
	switch(m_iShowPropertyEvent)
	{
		case APL_MESSAGE_SEND_EVENT:	//Отправили из черновиков		
			for(i=0; i<doc->m_items.GetSize(); i++)
			{
				if(doc->m_items[i]->m_type==APL_TREE_ITEM_MESSAGE)
				{
					CaplMessageTreeItem *mesItem= (CaplMessageTreeItem*)doc->m_items[i];
					HTREEITEM perItem= mesItem->m_tree->GetParentItem(mesItem->m_item);
					inst= mesItem->m_message;
					CTreeCtrl* tree= mesItem->m_tree;
					doc_data.GetAttrBN(inst, S::status, buf);
					if(buf!=_T("draft") && doc->m_user_drafted_folder->m_item == perItem)
					{
						doc->m_items.Remove(i);
						i--;
						CaplMessageTreeItem *message_item=
							new CaplMessageTreeItem(tree, doc, inst);
						m_iNameFormate= APL_MESSAGE_SENDED_FORMATE;
						message_item->CreateTreeItem(doc->m_user_sended_folder->m_item);
						tree->SetRedraw();
					}
				}
			}
			break;
		case APL_MESSAGE_ADD_EVENT:		//Ответили - Переправили
			ShowAllMessages(doc);
			break;
		case APL_MESSAGE_DELETE_EVENT:	//Что-то удалили...
			for(i=0; i<doc->m_items.GetSize(); i++)
			{
				if(doc->m_items[i]->m_type==APL_TREE_ITEM_MESSAGE)
				{
					CaplMessageTreeItem *mesItem= (CaplMessageTreeItem*)doc->m_items[i];
					CaplInstance* inst,
						*mes= mesItem->m_message;
					HTREEITEM perItem= mesItem->m_tree->GetParentItem(mesItem->m_item);
					CaplInstance* person= doc->m_api.m_appr_mgr.GetCurrentPerson();
				
					bool bDel= false;
					
					if(mes->GetType()==NULL)
					{
						bDel= true;
					}
					else
					{
						doc_data.GetAttr(mes, doc->m_api.m_message_mgr.a_message_sender, inst);
						if(person==inst)
						{
							bool bKill;
							doc_data.GetAttr(mes, doc->m_api.m_message_mgr.a_message_sender_kill, bKill);
							doc_data.GetAttr(mes, doc->m_api.m_message_mgr.a_message_sender_folder, inst);
							
							if(bKill || (mesItem->m_folder!=inst))
							{
								bDel= true;
								if((doc->m_user_drafted_folder&&doc->m_user_drafted_folder->m_item == perItem) ||
									(doc->m_user_sended_folder&&doc->m_user_sended_folder->m_item == perItem))
								{
									doc->m_send_or_dr_messages.Remove(doc->m_send_or_dr_messages.Find(mes));
								}
							}
						}

						doc_data.GetAttr(mes, doc->m_api.m_message_mgr.a_message_recipient, inst);
						if(person==inst)
						{
							bool bKill;
							doc_data.GetAttr(mes, doc->m_api.m_message_mgr.a_message_recipient_kill, bKill);						
							doc_data.GetAttr(mes, doc->m_api.m_message_mgr.a_message_recipient_folder, inst);
							
							if(bKill || (mesItem->m_folder!=inst))
							{
								bDel= true;
								if(doc->m_user_incoming_folder->m_item == perItem)
								{
									doc->m_incoming_messages.Remove(doc->m_incoming_messages.Find(mes));
								}
							}
						}
					}
	
					if(bDel)
					{
						doc->m_items.Remove(i);
						i--;
					}
				}
			}
			break;
		case APL_MESSAGE_NO_EVENT:		//Ничего не произошло
			break;
	}

	m_iShowPropertyEvent= APL_MESSAGE_NO_EVENT;
}

bool CaplMessageTreeItem::ShowItems()
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL

	if(m_message)
	{
		// Не показываем кому не надо
		if(!m_doc->m_api.m_message_mgr.IsUserSenderOrRecipient(m_message)) return false;


		m_tree->SetRedraw(FALSE);
		
//		ShowMessageHistory();

		int i;
		aplExtent ext;
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_items, ext);

		if(m_doc->m_bUseProject)
		{		
			aplExtent ext_projects;
			for(i=0;i<ext.Size;i++)
			{
				if(m_doc_data.IsKindOf(ext[i], m_doc->m_project_mgr->e_project))
				{
					ext_projects.Add(ext[i]);
				}
			}
			m_doc->m_project_mgr->LoadProjectInfo(ext_projects);
		}
		m_doc->m_api.m_message_mgr.LoadExtentInfo(ext);

		for(i= 0; i<ext.GetSize(); i++)
		{
			if(-1==m_items.Find(ext[i]))
			{
				CaplTreeItem* aplItem= NULL;
				InsertInstInTree(ext[i], m_item, m_doc, m_tree, m_items, 
					NULL, &aplItem);
				m_items.Add(ext[i]);
			}
		}

		m_tree->SetRedraw();
		if(m_ExecMyExpand)
			MyExpand(false);
	}
	return true;
}

bool CaplMessageTreeItem::PasteItem(CaplTreeItem *item, CPoint *point)
{
	if(item==0) return false;
	if(m_tree==0) return false;
	if(m_doc==0) return false;
	CaplAggr aggr;
	if(m_message!=0)
	{
		CString buf;
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_status, buf);
		if(buf!=_T("draft")) return true;
//		m_doc->m_api.m_message_mgr.LoadMessageInfo(m_message);
		m_doc_data.GetAttr(m_message, m_doc->m_api.m_message_mgr.a_message_items, aggr);
	}
	else return false;
	CaplInstance* inst= NULL;
	aplExtent ext;
	item->GetMainInstances(ext);
	if(ext.Size<1) return false;
	inst=ext[0];
	if(inst==0) return false;
	if(inst->GetAccessmode()>aplRO) return false;
	m_tree->SetRedraw(FALSE);
	bool bIsNew= true;
	for(int i= 0; i<aggr.GetSize(); i++)
	{
		CaplInstance* inst1= NULL;
		aggr.GetByIndex(i, inst1);
		if(inst==inst1) bIsNew= false;
	}
	if(bIsNew)
	{
		aggr.Add(inst);
		m_doc_data.PutAttr(m_message, m_doc->m_api.m_message_mgr.a_message_items, aggr);
		m_doc_data.NET_SaveChanges();
	}
	ShowItems();
	MyExpand();
	m_tree->SetRedraw();
	return true;
}

bool CaplMessageTreeItem::CheckMessages(CPSMDoc* doc)
{
	bool bRes= false; 
/*
	CaplInstance* inst;
	CaplInstance* person=doc_data.GetCurrUser();
	doc_data.GetAttrBN(person, _T("personality"), inst);
	if(!inst) return false;
//	doc_data.GetAttrBN(inst, _T("the_person"), person);
	if(doc_data.IsKindOf(inst, doc->m_api.m_appr_mgr.e_pers_org)){
		doc_data.GetAttr(inst, doc->m_api.m_appr_mgr.a_po_the_pers , person);
	}else if(doc_data.IsKindOf(inst,doc->m_api.m_appr_mgr.e_person)){
		person=inst;
	}else{
		person=0;
	}

	if(!person) return false;

	CaplAttrValue val[3];
	aplExtent ext;
	
	val[0].value.Set(person);
	val[0].attr= doc->m_api.m_message_mgr.a_message_recipient;
	val[1].value.Set(_T("sendet"));
	val[1].attr= doc->m_api.m_message_mgr.a_message_status;
	inst= NULL;
	CString buf= _T("");
	val[2].value.Set(buf);
	val[2].attr= doc->m_api.m_message_mgr.a_message_date_received;

	doc_data.NET_FindInstancesWithAttrValues(doc->m_api.m_message_mgr.e_message, 3, &val[0], ext, false);
	
	if(0!=ext.GetSize())
		bRes= true;
	
	if(!bRes)
	{
		ext.Clear();
		
		val[0].value.Set(_T("sendet"));
		val[0].attr= doc->m_api.m_message_mgr.a_message_status;
		CaplInstance* prs= NULL;
		val[1].value.Set(prs);
		val[1].attr= doc->m_api.m_message_mgr.a_message_recipient;

		doc_data.NET_FindInstancesWithAttrValues(doc->m_api.m_message_mgr.e_message, 
			2, &val[0], ext, false);

		if(ext.GetSize())
		{
			CaplLoadData ld(&doc->m_api.m_data,DEF_SOURCE);
			for(int i= 0; i<ext.GetSize(); i++)
			{
				ld.AddQuery(0, ext[i]);
			}

			ld.AddQuery(_T('d'), 0, 0, doc->m_api.m_message_mgr.a_message_rec_offisial, true);
			ld.LoadEx();

			aplExtent offisials;
			doc->m_api.m_appr_mgr.GetPersonOfficials(person, offisials);
			bool bNew= false;
			for(i= 0; i<ext.GetSize() && !bNew; i++)
			{
				doc_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_rec_offisial, inst);
				for(int j= 0; j<offisials.GetSize(); j++)
				{
					if(offisials[j]==inst)
					{
						bRes= true; bNew= true; break;
					}
				}
			}
		}
	}
		*/	
	aplExtent		aeMail;
	CaplInstance*	ciPerson	=NULL;
	CaplInstance*	cit1		=NULL;
	CString			cst1;
	aplExtent		m_aeFindRes;
	//doc_data
	ciPerson=doc->m_api.m_appr_mgr.GetCurrentPerson();
	if(!ciPerson)
		return false;
	return doc->m_api.m_message_mgr.GetPersonIncomingMessages(aeMail,ciPerson,false,false,false);
//			for(i=0;i<aeMail.GetSize();i++)
//			{
//				cit1=aeMail.GetAt(i);
//				doc->m_api.m_data.GetAttr(cit1,doc->m_api.m_message_mgr.a_message_status,cst1);
//				
//				if(_T("readed")!=cst1&&_T("replyed")!=cst1)
//					return true;
//			}
//			//str.Format(APL_T("Непрочитанные (%d)"),m_aeFindRes.GetSize()); 
//
//
// 	return false;
}

bool CaplMessageTreeItem::NewMessageNotify(CPSMDoc *doc)
{
	bool bRes= false;

	CaplInstance* person=doc->m_api.m_appr_mgr.GetCurrentPerson();

	if(!person) return false;

	CaplAttrValue val[3];
	aplExtent ext;
	
	val[0].value.Set(person);
	val[0].attr= doc_data.GetAttrDefinition(doc->m_api.m_message_mgr.e_message, S::recipient);
	val[1].value.Set(_T("sendet"));
	val[1].attr= doc_data.GetAttrDefinition(doc->m_api.m_message_mgr.e_message, S::status);
/*	inst= NULL;
	val[2].value.Set(inst);
	val[2].attr= doc_data.GetAttrDefinition(doc->m_api.m_message_mgr.e_message, S::date_received);*/

	doc_data.NET_FindInstancesWithAttrValues(doc->m_api.m_message_mgr.e_message, 2, &val[0], ext, false);
	
	if(0!=ext.GetSize())
		bRes= true;
	else
	{
		ext.Clear();
		aplExtent offisials;
		doc->m_api.m_appr_mgr.GetPersonOfficials(person, offisials);
		bool bLoad= false;

		for(int j= 0; j<offisials.GetSize(); j++)
		{			
			val[0].value.Set(offisials[j]);
			val[0].attr= doc->m_api.m_message_mgr.a_message_rec_offisial;
			val[1].value.Set(_T("sendet"));
			val[1].attr= doc->m_api.m_message_mgr.a_message_status;
			CaplInstance* prs= NULL;
			val[2].value.Set(prs);
			val[2].attr= doc->m_api.m_message_mgr.a_message_recipient;

			doc_data.NET_FindInstancesWithAttrValues(doc->m_api.m_message_mgr.e_message, 3, &val[0], ext, false);
			
			if(0!=ext.GetSize())
			{
				bRes= true;
				break;
			}
		}
	}
	return bRes;
}

bool CaplMessageTreeItem::ShowLostMessages(CPSMDoc* doc)
{
	if(!doc) return false;
	if(!doc_data.IsConnected()) return false;
	if(!doc->m_user_incoming_folder) return false;
	if(!doc->m_user_sended_folder) return false;
	if(!doc->m_user_drafted_folder) return false;

	aplExtent ext;
	
	CaplInstance* person=doc->m_api.m_appr_mgr.GetCurrentPerson();
	if(!person) return false;

	doc->m_api.m_message_mgr.GetAllLostMessages(ext);

	for(int i= 0; i<ext.Size; i++)
	{
		if(-1==doc->m_incoming_messages.Find(ext[i]))
		{
			m_iNameFormate= APL_MESSAGE_INCOMING_FORMATE;
			
			CaplMessageTreeItem *message_item=
				new CaplMessageTreeItem(doc->m_user_incoming_folder->m_tree, 
				doc, ext[i]);
			message_item->m_bLostMessage= true;
			message_item->CreateTreeItem(doc->m_user_incoming_folder->m_item);
			doc->m_incoming_messages.Add(ext[i]);
		}
	}
	return true;
}

CString CaplMessageTreeItem::GetMessageRecip(CPSMDoc *doc, CaplInstance *message)
{
	if(!doc) return _T("");
	if(!doc->m_api.m_data.IsConnected()) return _T("");
	if(!message) return _T("");
	if(!message->GetType()) return _T("");

	CString sName;

	aplExtent copyMessages;
	doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_copies, copyMessages);
	
	CaplInstance* person= NULL;
	CString str;

	if(!copyMessages.GetSize())
	{
		doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_rec_offisial, person);
		if(!person) doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_recipient, person);
		if(!person)
		{
			doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_rec_nick, str);
			if(!str.IsEmpty()) sName.Format(_T("e-mail \"%s\""), str);
		}
		//else doc->m_api.m_appr_mgr.GetPersonName(person, sName);
		else doc->m_api.GetItemName(person, sName);
	}
	else
	{
		doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_rec_offisial, person);
		if(!person) doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_recipient, person);
		//if(person) doc->m_api.m_appr_mgr.GetPersonName(person, sName);
		if(person) doc->m_api.GetItemName(person, sName);
		
		for(int n= 0; n<copyMessages.GetSize(); n++)
		{
			if(sName.GetLength()>40){sName+=_T(" ..."); break;}
			if(!sName.IsEmpty()) sName+=_T("; "); 

			person= NULL;
			doc->m_api.m_data.GetAttr(copyMessages[n], doc->m_api.m_message_mgr.a_message_rec_offisial, person);
			if(!person) doc->m_api.m_data.GetAttr(copyMessages[n], doc->m_api.m_message_mgr.a_message_recipient, person);
			//if(person){doc->m_api.m_appr_mgr.GetPersonName(person, str); sName+=str;}
			if(person){doc->m_api.GetItemName(person, str); sName+=str;}
		}	
	}
	return sName;
}

CString CaplMessageTreeItem::GetMessageSend(CPSMDoc *doc, CaplInstance *message)
{
	if(!doc) return _T("");
	if(!doc->m_api.m_data.IsConnected()) return _T("");
	if(!message) return _T("");
	if(!message->GetType()) return _T("");
	
	CString sName;
	CaplInstance* person= NULL;
	CString str;
	
	doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_sender, person);
	if(!person)
	{
		doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_send_nick, str);
		if(!str.IsEmpty()) sName.Format(_T("e-mail \"%s\""), str);
		if(sName.IsEmpty()) sName=  APL_T("Системное сообщение");
	}
	//else doc->m_api.m_appr_mgr.GetPersonName(person, sName);
	else doc->m_api.GetItemName(person, sName);
	return sName;
}
