// MailListView.cpp : implementation file
//

#include "stdafx.h"
#include "psm.h"
#include "PSMDoc.h"
#include "MailListView.h"
#include "MailRTFView.h"
#include "MailFrame.h"
#include "aplMessageTreeItem.h"
#include "TreeProductItem.h"
#include "aplFolderTreeItem.h"
#include "aplDocTreeItem.h"

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

/////////////////////////////////////////////////////////////////////////////
// CMailListView

IMPLEMENT_DYNCREATE(CMailListView, CaplListView)

CMailListView::CMailListView()
{
	m_iShowLostMes= 0;
	m_iShowDeletedMes= 0;
	m_iShowFolderMes= 0;
	
	m_iSubItem= 4;
	m_ssDefault= ASCENDING;

	m_content_body= NULL;
	m_cur_item= NULL;
}

CMailListView::~CMailListView()
{
	
}


BEGIN_MESSAGE_MAP(CMailListView, CaplListView)
	//{{AFX_MSG_MAP(CMailListView)
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONDBLCLK()
	ON_COMMAND(ID_MESSAGE_DELIVER, OnMessageDeliver)
	ON_UPDATE_COMMAND_UI(ID_MESSAGE_DELIVER, OnUpdateMessageDeliver)
	ON_COMMAND(ID_MESSAGE_FORWARD, OnMessageForward)
	ON_UPDATE_COMMAND_UI(ID_MESSAGE_FORWARD, OnUpdateMessageForward)
	ON_COMMAND(ID_MESSAGE_PRINT, OnMessagePrint)
	ON_UPDATE_COMMAND_UI(ID_MESSAGE_PRINT, OnUpdateMessagePrint)
	ON_COMMAND(ID_MESSAGE_REPLY, OnMessageReply)
	ON_UPDATE_COMMAND_UI(ID_MESSAGE_REPLY, OnUpdateMessageReply)
	ON_COMMAND(ID_MESSAGE_SEND, OnMessageSend)
	ON_UPDATE_COMMAND_UI(ID_MESSAGE_SEND, OnUpdateMessageSend)
	ON_COMMAND(ID_MESSAGE_DELETE, OnMessageDelete)
	ON_UPDATE_COMMAND_UI(ID_MESSAGE_DELETE, OnUpdateMessageDelete)
	ON_COMMAND(ID_MESSAGE_READ, OnMessageRead)
	ON_UPDATE_COMMAND_UI(ID_MESSAGE_READ, OnUpdateMessageRead)
	ON_COMMAND(ID_SHOW_MESSAGE_ITEMS, OnShowMessageItems)
	ON_UPDATE_COMMAND_UI(ID_SHOW_MESSAGE_ITEMS, OnUpdateShowMessageItems)
	ON_COMMAND(ID_NEW_MESSAGE_CREATE, OnNewMessageCreate)
	ON_UPDATE_COMMAND_UI(ID_NEW_MESSAGE_CREATE, OnUpdateNewMessageCreate)
	ON_WM_DESTROY()
	ON_COMMAND(ID_SHOW_DELETED_MESSAGES, OnShowDeletedMessages)
	ON_UPDATE_COMMAND_UI(ID_SHOW_DELETED_MESSAGES, OnUpdateShowDeletedMessages)
	ON_COMMAND(ID_SHOW_LOST_MESSAGES, OnShowLostMessages)
	ON_UPDATE_COMMAND_UI(ID_SHOW_LOST_MESSAGES, OnUpdateShowLostMessages)
	ON_COMMAND(ID_SHOW_FOLDER_MESSAGES, OnShowFolderMessages)
	ON_UPDATE_COMMAND_UI(ID_SHOW_FOLDER_MESSAGES, OnUpdateShowFolderMessages)
	//}}AFX_MSG_MAP
	ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, OnMessagechanged)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMailListView drawing

void CMailListView::OnDraw(CDC* pDC)
{
	CPSMDoc* pDoc = GetDocument();
	// TODO: add draw code here
}

/////////////////////////////////////////////////////////////////////////////
// CMailListView diagnostics

#ifdef _DEBUG
void CMailListView::AssertValid() const
{
	CaplListView::AssertValid();
}

void CMailListView::Dump(CDumpContext& dc) const
{
	CaplListView::Dump(dc);
}

CPSMDoc* CMailListView::GetDocument() // non-debug version is inline
{
	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CPSMDoc)));
	return (CPSMDoc*)m_pDocument;
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CMailListView message handlers

void CMailListView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) 
{	
	
}

void CMailListView::OnInitialUpdate() 
{
	CaplListView::OnInitialUpdate();
	SetUniqueName(_T("pss_mail_view"));

	CListCtrl* list= &GetListCtrl();
	list->SetExtendedStyle(list->GetExtendedStyle()|
		LVS_EX_FULLROWSELECT|LVS_EX_SUBITEMIMAGES|LVS_EX_INFOTIP/*|LVS_EX_GRIDLINES*/);

	list->ModifyStyle(0,LVS_SHOWSELALWAYS,0);
	
	list->SetImageList(aplGetInstImageList(), LVSIL_SMALL);
	
	list->InsertColumn(0, _T(""), LVCFMT_LEFT, 25);
	list->InsertColumn(1,  APL_T("От"), LVCFMT_LEFT, 100);
	list->InsertColumn(2,  APL_T("Тема"), LVCFMT_LEFT, 200);
	list->InsertColumn(3,  APL_T("Получено"), LVCFMT_LEFT, 130);
	list->InsertColumn(4,  APL_T("Отправлено"), LVCFMT_LEFT, 130);

	m_iShowDeletedMes= AfxGetApp()->GetProfileInt(_T("MessageView"), _T("ShowDeletedMes"), 0);
	m_iShowFolderMes= AfxGetApp()->GetProfileInt(_T("MessageView"), _T("ShowFolderMes"), 0);
	m_iShowLostMes= AfxGetApp()->GetProfileInt(_T("MessageView"), _T("ShowLostMes"), 0);
	
	m_iSubItem= AfxGetApp()->GetProfileInt(_T("MessageView"), _T("SortSubItem"), 4);
	m_ssDefault= (SORT_STATE)AfxGetApp()->GetProfileInt(_T("MessageView"), _T("SortState"), 16);

	EmptyArray(m_aCombinedSortedColumns);
	SetItemSortState(m_iSubItem, m_ssDefault);

	aplInstallFindInTable(this);
}

void CMailListView::UpdateTreeItem(CaplTreeItem *item)
{
	m_cur_item=item;
	CListCtrl* list= &GetListCtrl();
	if(!list) return;
	GetListCtrl().DeleteAllItems();
	if(item==0) return;	
	
	CPSMDoc* doc= GetDocument();
	if(doc==0) return;

	CString sItemName;
	item->GetName(sItemName);
	if(sItemName== APL_T("Входящие")) ResetHeader(APL_MESSAGE_INCOMING_FORMATE);
	else ResetHeader(APL_MESSAGE_SENDED_FORMATE);
	
//	CaplMessageTreeItem::ShowAllMessages(doc);
	UpdateView();
}

void CMailListView::UpdateView()
{
	if(!m_content_body) return;
	CMailRTFView* content_view= (CMailRTFView*)m_content_body->GetActiveView();
	if(content_view)content_view->UpdateBody(NULL);
	m_content_body->UpdateHeader(_T(""), _T(""), _T(""));

	CListCtrl* list= &GetListCtrl();
	if(!list) return;
	GetListCtrl().DeleteAllItems();

	CPSMDoc* doc= GetDocument();
	if(doc==0) return;
	if(m_cur_item==0) return;

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

	CString sItemName;
	m_cur_item->GetName(sItemName);
	if(sItemName== APL_T("Почта")) sItemName= m_CurTabName;
	
	bool b1= false, b2= false, b3= false;
	if(m_iShowDeletedMes) b1= true;
	if(m_iShowLostMes) b2= true;
	if(m_iShowFolderMes) b3= true;

	aplExtent mesExt;
	if(m_cur_item->m_type==APL_TREE_ITEM_FOLDER || m_cur_item->m_type==APL_TREE_ITEM_DOCUMENT)
	{
		aplExtent ext;

		if(m_cur_item->m_type==APL_TREE_ITEM_FOLDER)
		{
			doc->m_api.m_folder_mgr.GetFolderContents(((CaplFolderTreeItem*)m_cur_item)->m_inst, ext);
		}
		else if ( m_cur_item->m_type==APL_TREE_ITEM_DOCUMENT)
		{
			CaplDocTreeItem *docitem=(CaplDocTreeItem*)m_cur_item;

			CaplInstance *inst=docitem->m_inst;
			if(0!=docitem->m_rev)inst=docitem->m_rev;
			m_cur_item->FindContainedMessage(inst, ext);
		}
		
		CaplInstance* person= doc->m_api.m_appr_mgr.GetCurrentPerson();
		CaplInstance* sender, *recipient;
		bool bRecKill, bSendKill;

		for(int i= 0; i<ext.GetSize(); i++)
		{
			if(!doc->m_api.m_data.IsKindOf(ext[i], doc->m_api.m_message_mgr.e_message)) continue;

			if(!m_iShowDeletedMes)
			{
				bRecKill= false; bSendKill= false;

				doc->m_api.m_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_sender, sender);
				doc->m_api.m_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_recipient, recipient);
				doc->m_api.m_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_sender_kill, bSendKill);
				doc->m_api.m_data.GetAttr(ext[i], doc->m_api.m_message_mgr.a_message_recipient_kill, bRecKill);
				
				if(person==sender && bSendKill) continue;
				if(person==recipient && bRecKill) continue;
			}

			mesExt.Add(ext[i]);
		}
		
		if(mesExt.GetSize()) doc->m_api.m_message_mgr.LoadMessageInfo(mesExt);
	}
	else if(sItemName== APL_T("Входящие"))
	{
		doc->m_api.m_message_mgr.GetPersonIncomingMessages(mesExt, person, b1, b2, b3);
	}
	else if(sItemName== APL_T("Отправленные"))
	{
		doc->m_api.m_message_mgr.GetPersonSendedMessages(mesExt, person, b1, b3);
	}
	else if(sItemName== APL_T("Черновики"))
	{
		doc->m_api.m_message_mgr.GetPersonDraftedMessages(mesExt, person, b3);
	}

	if(sItemName== APL_T("Входящие")) InsertMessages(APL_MESSAGE_INCOMING_FORMATE, mesExt);
	else InsertMessages(APL_MESSAGE_SENDED_FORMATE, mesExt);
}

void CMailListView::ResetHeader(long mode)
{
	CListCtrl* list= &GetListCtrl();
	while(list->GetHeaderCtrl()->GetItemCount())
		list->DeleteColumn(0);
	
	list->InsertColumn(0, _T(""), LVCFMT_LEFT, 25);
	if(mode==APL_MESSAGE_INCOMING_FORMATE)
		list->InsertColumn(1,  APL_T("От"), LVCFMT_LEFT, 120);
	else 
		list->InsertColumn(1,  APL_T("Кому"), LVCFMT_LEFT, 120);
	list->InsertColumn(2,  APL_T("Тема"), LVCFMT_LEFT, 230);
	list->InsertColumn(3,  APL_T("Получено"), LVCFMT_LEFT, 130);
	list->InsertColumn(4,  APL_T("Отправлено"), LVCFMT_LEFT, 130);	
	
	SetColumnDate(3);
	SetColumnDate(4);

//	SetColumnDateTime(3);
//	SetColumnDateTime(4);
}

void CMailListView::InsertMessages(long mode, aplExtent& messages)
{
	CSortListCtrl* list= (CSortListCtrl*)&GetListCtrl();
	
	CPSMDoc* doc= GetDocument();
	if(doc==0) return;
	
	CString name, buf, buf1;
	CaplInstance* person= NULL, *inst= NULL;
	
	list->SetRedraw(FALSE);

	for(int i= 0; i<messages.GetSize(); i++)
	{
		if(!messages[i] || !messages[i]->GetType()) continue;
		doc->m_api.m_data.GetAttr(messages[i], doc->m_api.m_message_mgr.a_message_status, buf);
		doc->m_api.m_data.GetAttr(messages[i], doc->m_api.m_message_mgr.a_message_forward, inst);

		aplExtent copyMessages;
		doc->m_api.m_data.GetAttr(messages[i], doc->m_api.m_message_mgr.a_message_copies, copyMessages);
		
		UINT ico= ICON_MESSAGES+4;
		buf1=  APL_T("  Не прочитано");		

		if(buf==_T("draft")){/*та же иконка*/ ico-=0;}
		else if(copyMessages.GetSize()==0)
		{
			if(buf==_T("readed"))
			{
				ico+=1;buf1=  APL_T(" Прочитано");
				if(inst) {ico+=2;buf1=  APL_T(" Переправлено");}
			}
			else if(buf==_T("replyed")) 
			{
				ico+=2;buf1=  APL_T(" Отвечено");
				if(inst) ico+=2;
			}
		}
		else
		{
			ico+=6;buf1=  APL_T(" Рассылка");
		}
		
		int m= list->InsertItem(i, buf1, ico);
		list->SetItemData(m, (DWORD)messages[i]);		

		buf= _T("");
		if(mode==APL_MESSAGE_SENDED_FORMATE)
		{
			buf= CaplMessageTreeItem::GetMessageRecip(doc, messages[i]);
		}
		else
		{
			buf= CaplMessageTreeItem::GetMessageSend(doc, messages[i]);
		}
		list->SetItemText(m, 1, buf);

		doc->m_api.m_data.GetAttr(messages[i], doc->m_api.m_message_mgr.a_message_subject, buf);
		list->SetItemText(i, 2, buf);

		COleDateTime odt;
		doc->m_api.m_data.GetAttr(messages[i], doc->m_api.m_message_mgr.a_message_date_send, buf);
		if(!buf.IsEmpty())
		{
			aplString2Date(buf, odt);	
			buf= odt.Format(_T("%d/%m/%Y  %H:%M:%S"));//27/02/2007 18:25:00
			list->SetItemText(i, 4, buf);
		}

		if(copyMessages.GetSize()==0)
		{
			doc->m_api.m_data.GetAttr(messages[i], 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:%S"));
				list->SetItemText(i, 3, buf);
			}
		}
		else
		{
			list->SetItemText(i, 3, _T("*"));
		}
	}

	list->SetRedraw(TRUE);

	if(!IsSorting())
	{
		int iCurItem= m_aCombinedSortedColumns[0];
		if(iCurItem>=0)
		{
			m_iSubItem= iCurItem;
			m_ssDefault= GetItemSortState(m_iSubItem);
		}

		SetItemSortState(m_iSubItem, (SORT_STATE)!m_ssDefault);
		SortColumn(m_iSubItem, SINGLE_COLUMN_SORT);
	}
}

void CMailListView::OnLButtonDown(UINT nFlags, CPoint point) 
{
	CPSMDoc* doc= GetDocument();
	if(!doc) return;
	if(!doc->m_api.m_data.IsConnected()) return;

	UINT flag;
    int clickItem= GetListCtrl().HitTest(point, &flag);
	if(-1==clickItem)
	{
		CMailRTFView* content_view= (CMailRTFView*)m_content_body->GetActiveView();
		if(content_view)content_view->UpdateBody(NULL);
		m_content_body->UpdateHeader(_T(""), _T(""), _T(""));
	}

	CaplListView::OnLButtonDown(nFlags, point);
}

void CMailListView::OnLButtonDblClk(UINT nFlags, CPoint point) 
{
	CPSMDoc* doc= GetDocument();
	if(!doc) return;
	if(!doc->m_api.m_data.IsConnected()) return;

	UINT flag;
    int clickItem= GetListCtrl().HitTest(point, &flag);
	if(-1!=clickItem)
	{
		CaplInstance* message= (CaplInstance*)GetListCtrl().GetItemData(clickItem);
		doc->m_api.m_message_mgr.ShowMessageProperty(message);
	}
	
	CaplListView::OnLButtonDblClk(nFlags, point);
}

void CMailListView::OnMessagechanged(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;

	int clickItem= pNMListView->iItem;
	if(pNMListView->uNewState==3)
	{
		CPSMDoc* doc= GetDocument();
		if(!doc) return;
		if(!doc->m_api.m_data.IsConnected()) return;
		
		CaplInstance* message= NULL;	
		if(-1!=clickItem)
		{
			message= (CaplInstance*)GetListCtrl().GetItemData(clickItem);

			m_content_body->ShowMessage(message, 0);
			
			/*CMailRTFView* content_view= (CMailRTFView*)m_content_body->GetActiveView();
			if(content_view)content_view->UpdateBody(message);
			
			CString sFrom, sTo, sSubject, buf;
			
			sFrom= CaplMessageTreeItem::GetMessageSend(doc, message);
			sTo= CaplMessageTreeItem::GetMessageRecip(doc, message);
			doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_subject, sSubject);
			
			m_content_body->UpdateHeader(sFrom, sTo, sSubject);*/
		}
	}

	*pResult = 0;
}


void CMailListView::OnMessageDeliver() 
{
	CPSMDoc* doc= GetDocument();
	if(!doc || !doc->m_api.m_data.IsConnected()) return;

	//CaplMessageTreeItem::ShowAllMessages(doc);
	UpdateView();
}

void CMailListView::OnUpdateMessageDeliver(CCmdUI* pCmdUI) 
{
	
}

bool CMailListView::CheckMailMenu(bool &is_draft)
{
	bool retval = false;
	CaplInstance* message;
	aplExtent messages;
	CString status;
	int item = -1;
	is_draft = false;
	CPSMDoc* doc= GetDocument();

	while((item= GetListCtrl().GetNextItem(item, LVIS_SELECTED))>-1)
	{
		message= (CaplInstance*)GetListCtrl().GetItemData(item);
		if(message==0) continue;
		doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_status, status);
		if(status == _T("draft")) is_draft = true;
		retval = true;
	}
	return retval;
}

void CMailListView::GetStateAdd2AddressBook(bool &is_recipi, bool &is_sender) 
{
	is_recipi = false;
	is_sender = false;

	CPSMDoc* doc= GetDocument();
	if(!doc|| !doc->m_api.m_data.IsConnected()) return;

	int item= GetListCtrl().GetNextItem(-1, LVIS_SELECTED);
	if(item==-1) return;
	int item2= GetListCtrl().GetNextItem(item, LVIS_SELECTED);
	// если выделено больше одного сообщения - мы не знаем, из какого брать получателе-отправителя.
	if(item2!=-1) return;

	CaplInstance* sender, *recipient, *recipient_off;
	CaplInstance* message = (CaplInstance*)GetListCtrl().GetItemData(item);
	CaplInstance* person = doc->m_api.m_appr_mgr.GetCurrentPerson();

	if(person == 0 || message == 0) return;

	doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_sender, sender);
	doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_recipient, recipient);
	doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_rec_offisial, recipient_off);

	if(person!=recipient)
	{
		if(recipient!=0) is_recipi = true;
	}
	if(person!=recipient_off && recipient_off!=0)
	{
		is_recipi = true;
	}
	if(person!=sender && sender!=0)
	{
		is_sender = true;
	}
}

void CMailListView::DeleteMessages()
{
	CPSMDoc* doc= GetDocument();
	if(!doc|| !doc->m_api.m_data.IsConnected()) return;

	CaplInstance* message;
	aplExtent messages;
	int item = -1;

	while((item= GetListCtrl().GetNextItem(item, LVIS_SELECTED))>-1)
	{
		message= (CaplInstance*)GetListCtrl().GetItemData(item);
		if(message==0) continue;
		messages.Add(message);
	}

	if(messages.GetSize() == 0) return;

	if(AfxMessageBox( APL_T("Вы действительно хотите удалить сообщения?"),MB_YESNO)==IDYES)
	{
		bool bEndOperation=false;
		for(int i=0;i<messages.GetSize();i++)
		{
			doc->m_api.m_message_mgr.DeleteMessage(messages[i],&bEndOperation);
			if(bEndOperation) break;

		}
		doc->m_api.m_data.NET_SaveChanges();
		UpdateView();
	}
}

void CMailListView::Move2FromFolder(bool MoveInto)
{
	CPSMDoc* doc= GetDocument();
	if(!doc|| !doc->m_api.m_data.IsConnected()) return;

	CaplInstance* message;
	aplExtent messages;
	int item = -1;

	while((item= GetListCtrl().GetNextItem(item, LVIS_SELECTED))>-1)
	{
		message= (CaplInstance*)GetListCtrl().GetItemData(item);
		if(message==0) continue;
		messages.Add(message);
	}

	if(messages.GetSize() == 0) return;
	
	if(MoveInto)
	{
		if(doc->m_api.m_message_mgr.MoveMessages2Folder(messages))
		{
			doc->m_api.m_data.NET_SaveChanges();
			UpdateView();
		}
	}
	else
	{
		if(doc->m_api.m_message_mgr.RemoveMessagesFromFolder(messages))
		{
			doc->m_api.m_data.NET_SaveChanges();
			UpdateView();
		}
	}
	((CaplFolderTreeItem*)m_cur_item)->Expand(1);
	((CaplFolderTreeItem*)m_cur_item)->Expand(2);
}

void CMailListView::Add2AddressBook(int command) 
{
	CPSMDoc* doc= GetDocument();
	if(!doc|| !doc->m_api.m_data.IsConnected()) return;

	int item= GetListCtrl().GetNextItem(-1, LVIS_SELECTED);
	CaplInstance* sender, *recipient, *recipient_off;
	CaplInstance* message= (CaplInstance*)GetListCtrl().GetItemData(item);
	CaplInstance* person = doc->m_api.m_appr_mgr.GetCurrentPerson();

	if(person == 0 || message == 0) return;

	doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_sender, sender);
	doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_recipient, recipient);
	doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_rec_offisial, recipient_off);

	if(command == ID_ADD2ADDRESS_BOOK_RECIPI)
	{
		if(recipient!=0)
		{
			if(doc->m_api.m_message_mgr.Add2AddressBook(recipient))
			{
				AfxMessageBox(S::message_add2address_recipient_performed());
			}
		}
		else if(recipient_off!=0)
		{
			if(doc->m_api.m_message_mgr.Add2AddressBook(recipient_off))
			{
				AfxMessageBox(S::message_add2address_recipient_performed());
			}
		}
	}
	else if(command == ID_ADD2ADDRESS_BOOK_SENDER)
	{
		if(doc->m_api.m_message_mgr.Add2AddressBook(sender))
		{
			AfxMessageBox(S::message_add2address_sender_performed());
		}
	}
}

void CMailListView::OnMessageForward() 
{
	CPSMDoc* doc= GetDocument();
	if(!doc|| !doc->m_api.m_data.IsConnected()) return;
	
	int item= GetListCtrl().GetNextItem(-1, LVIS_SELECTED);
	CaplInstance* message= (CaplInstance*)GetListCtrl().GetItemData(item);
	doc->m_api.m_message_mgr.Forward(message);	
}

void CMailListView::OnUpdateMessageForward(CCmdUI* pCmdUI) 
{
	int ind= -1, n= 0;		
	while((ind= GetListCtrl().GetNextItem(ind, LVIS_SELECTED))>-1)
		n++;

	if(n==1)
	{
		CPSMDoc* doc= GetDocument();
		if(!doc || !doc->m_api.m_data.IsConnected())
		{
			pCmdUI->Enable(FALSE);
			return;
		}
		
		CString buf;
		CaplInstance* mes= NULL;
		
		ind= GetListCtrl().GetNextItem(-1, LVIS_SELECTED);
		mes= (CaplInstance*)GetListCtrl().GetItemData(ind);
		if(mes)doc->m_api.m_data.GetAttr(mes, doc->m_api.m_message_mgr.a_message_status, buf);		
		
		if(buf.Compare(_T("draft")))pCmdUI->Enable(TRUE);
		else pCmdUI->Enable(FALSE);
	}
	else pCmdUI->Enable(FALSE);	
}

void CMailListView::OnMessageReply() 
{
	CPSMDoc* doc= GetDocument();
	if(!doc || !doc->m_api.m_data.IsConnected()) return;
	
	int item= GetListCtrl().GetNextItem(-1, LVIS_SELECTED);
	CaplInstance* message= (CaplInstance*)GetListCtrl().GetItemData(item);
	doc->m_api.m_message_mgr.Reply(message);
}

void CMailListView::OnUpdateMessageReply(CCmdUI* pCmdUI) 
{
	int ind= -1, n= 0;		
	while((ind= GetListCtrl().GetNextItem(ind, LVIS_SELECTED))>-1)
		n++;

	if(n==1)
	{
		CPSMDoc* doc= GetDocument();
		if(!doc || !doc->m_api.m_data.IsConnected())
		{
			pCmdUI->Enable(FALSE);
			return;
		}
		
		CString buf;
		CaplInstance* mes= NULL;
		
		ind= GetListCtrl().GetNextItem(-1, LVIS_SELECTED);
		mes= (CaplInstance*)GetListCtrl().GetItemData(ind);
		if(mes)doc->m_api.m_data.GetAttr(mes, doc->m_api.m_message_mgr.a_message_status, buf);		
		
		if(buf.Compare(_T("draft")))pCmdUI->Enable(TRUE);
		else pCmdUI->Enable(FALSE);
	}
	else pCmdUI->Enable(FALSE);
}

void CMailListView::OnMessageSend() 
{
	CPSMDoc* doc= GetDocument();
	if(!doc || !doc->m_api.m_data.IsConnected()) return;
	
	CListCtrl* list= &GetListCtrl();

	CaplInstance* message= NULL;
	
	int ind= -1, n= 0;

	bool bFlag1= doc->m_api.m_message_mgr.m_AutoSave;
	doc->m_api.SetAutoSave(false);

	while((ind= GetListCtrl().GetNextItem(ind, LVIS_SELECTED))>-1)
	{
		message= (CaplInstance*)GetListCtrl().GetItemData(ind);
		if(!message) continue;
		doc->m_api.m_message_mgr.SendDraftMessage(message, false);
		list->DeleteItem(ind);
		ind=-1;
	}

	CaplMessageTreeItem::m_iShowPropertyEvent= APL_MESSAGE_DELETE_EVENT;
	CaplMessageTreeItem::RefreshAllMessages(doc);

	doc->m_api.SetAutoSave(bFlag1);
	doc->m_api.SaveChanges();

	UpdateView();	
}

void CMailListView::OnUpdateMessageSend(CCmdUI* pCmdUI) 
{
	int ind= -1;
	if((ind= GetListCtrl().GetNextItem(ind, LVIS_SELECTED))==-1) pCmdUI->Enable(FALSE);
	else
	{
		CaplInstance* mes= (CaplInstance*)GetListCtrl().GetItemData(ind);
		CString buf;
		CPSMDoc* doc= GetDocument();
		doc->m_api.m_data.GetAttr(mes, doc->m_api.m_message_mgr.a_message_status, buf);
		
		if(!buf.Compare(_T("draft")))pCmdUI->Enable(TRUE);
		else pCmdUI->Enable(FALSE);
	}
}

void CMailListView::OnMessageDelete() 
{
	if(IDNO==MessageBox( APL_T("Вы действительно хотите удалить сообщения?"),  APL_T("Удаление сообщений"), MB_YESNO|MB_ICONWARNING))
		return;

	CPSMDoc* doc= GetDocument();
	if(!doc) return;
	
	CListCtrl* list= &GetListCtrl();

	CaplInstance* message= NULL;
	
	int ind= -1, n= 0;

	bool bFlag1= doc->m_api.m_AutoSave;
	bool bFlag2= doc->m_api.m_ModeInteractive;
	
	doc->m_api.SetAutoSave(false);
	
	while((ind= GetListCtrl().GetNextItem(ind, LVIS_SELECTED))>-1)
	{
		message= (CaplInstance*)GetListCtrl().GetItemData(ind);
		if(!message) continue;
		if(!doc->m_api.m_message_mgr.DeleteMessage(message))
			doc->m_api.SetModeInteractive(false);
		
		list->DeleteItem(ind);
		ind=-1;
	}
	
	CaplMessageTreeItem::m_iShowPropertyEvent= APL_MESSAGE_DELETE_EVENT;
	CaplMessageTreeItem::RefreshAllMessages(doc);

	doc->m_api.SetModeInteractive(bFlag2);
	doc->m_api.SetAutoSave(bFlag1);
	doc->m_api.SaveChanges();

	UpdateView();
	((CaplFolderTreeItem*)m_cur_item)->Expand(1);
	((CaplFolderTreeItem*)m_cur_item)->Expand(2);
}

void CMailListView::OnUpdateMessageDelete(CCmdUI* pCmdUI) 
{
	if(GetListCtrl().GetNextItem(-1, LVIS_SELECTED)!=-1) pCmdUI->Enable(TRUE);
	else pCmdUI->Enable(FALSE);	
}

void CMailListView::OnMessageRead() 
{
	CPSMDoc* doc= GetDocument();
	if(!doc) return;
	
	int item= GetListCtrl().GetNextItem(-1, LVIS_SELECTED);
	CaplInstance* message= (CaplInstance*)GetListCtrl().GetItemData(item);
	doc->m_api.m_message_mgr.ShowMessageProperty(message);	
}

void CMailListView::OnUpdateMessageRead(CCmdUI* pCmdUI) 
{
	int ind= -1, n= 0;
	while((ind= GetListCtrl().GetNextItem(ind, LVIS_SELECTED))>-1)
		n++;

	if(n==1) pCmdUI->Enable(TRUE);
	else pCmdUI->Enable(FALSE);	
}

void CMailListView::OnShowMessageItems() 
{
	CPSMDoc* doc= GetDocument();
	if(!doc) return;
	
	int item= GetListCtrl().GetNextItem(-1, LVIS_SELECTED);
	CaplInstance* message= (CaplInstance*)GetListCtrl().GetItemData(item);

	CMenu menu;  gSetPsmResourceHandle();
	VERIFY(menu.LoadMenu(IDR_PLUGINS_ID));
	CaplMenu::Install(this); // 	VERIFY(CaplMenu::Install(wnd, ePopupMenu ));
    CMenu* pPopup = menu.GetSubMenu(1);
    ASSERT(pPopup != NULL);
	if(pPopup==0) return;
	
	int iId;
	CString buf;
	
	aplExtent items;
	doc->m_api.m_data.GetAttr(message, doc->m_api.m_message_mgr.a_message_items, items);
	doc->m_api.LoadExtentInfo(items);
	
//	CToolBar tlbMenu;
//	tlbMenu.Create(this);

	for(int i= 0; i<items.GetSize(); i++)
	{
		iId= i+doc->m_nIndex;
		doc->m_api.GetItemName(items[i], buf);
		pPopup->InsertMenu(i, MF_BYPOSITION|MF_STRING, iId, buf);		
	}
	
	pPopup->RemoveMenu(ID_MESSAGEITEM_001, MF_BYCOMMAND);
// 	VERIFY(menu.LoadToolBar(IDR_MENU_ICONS));

	CPoint pnt;
	GetCursorPos(&pnt);
	int res = pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD,
						pnt.x, pnt.y, this);

	if((res-doc->m_nIndex)>-1 && (res-doc->m_nIndex)<items.GetSize())
	{
		CaplInstance* inst= items[res-doc->m_nIndex];
//		buf.Format( APL_T("Чувак, это [%s]"), inst->GetType()->name);
//		AfxMessageBox(buf);

		CPSMDoc* doc= GetDocument();
		if(!doc) return;
		if(doc->m_api.m_data.IsKindOf(inst,doc->m_api.m_doc_mgr.e_doc) ||
			doc->m_api.m_data.IsKindOf(inst,doc->m_api.m_doc_mgr.e_apl_doc_rev) ||
			doc->m_api.m_data.IsKindOf(inst,doc->m_api.m_doc_mgr.e_apl_stored_document))
		{
			doc->m_api.m_doc_mgr.View(inst);
		}
	}
}

void CMailListView::OnUpdateShowMessageItems(CCmdUI* pCmdUI) 
{
	int ind= -1;
	if((ind= GetListCtrl().GetNextItem(ind, LVIS_SELECTED))==-1) pCmdUI->Enable(FALSE);
	else
	{
		CaplInstance* mes= (CaplInstance*)GetListCtrl().GetItemData(ind);
		aplExtent items;
		CPSMDoc* doc= GetDocument();
		doc->m_api.m_data.GetAttr(mes, doc->m_api.m_message_mgr.a_message_items, items);
		pCmdUI->Enable(items.GetSize());
	}
}

void CMailListView::OnMessagePrint() 
{
	CMailRTFView* content_view= (CMailRTFView*)m_content_body->GetActiveView();
	if(content_view)content_view->OnPrintBody();
}

void CMailListView::OnUpdateMessagePrint(CCmdUI* pCmdUI) 
{
	int ind= -1, n= 0;
	while((ind= GetListCtrl().GetNextItem(ind, LVIS_SELECTED))>-1)
		n++;

	if(n==1) pCmdUI->Enable(TRUE);
	else pCmdUI->Enable(FALSE);	
}

void CMailListView::OnNewMessageCreate() 
{
	CPSMDoc* doc= GetDocument();
	if(!doc) return;

	aplExtent ext;
	CaplMessageTreeItem::CreateMessage(doc, NULL, ext);
	UpdateView();
}

void CMailListView::OnUpdateNewMessageCreate(CCmdUI* pCmdUI) 
{
	
}

void CMailListView::OnDestroy() 
{
	AfxGetApp()->WriteProfileInt(_T("MessageView"), _T("ShowDeletedMes"), m_iShowDeletedMes);
	AfxGetApp()->WriteProfileInt(_T("MessageView"), _T("ShowFolderMes"), m_iShowFolderMes);
	AfxGetApp()->WriteProfileInt(_T("MessageView"), _T("ShowLostMes"), m_iShowLostMes);
	
	m_iSubItem= m_aCombinedSortedColumns[0];
	SORT_STATE st= DESCENDING;

	if(m_iSubItem==-1) m_iSubItem= 4;
	
	m_ssDefault= GetItemSortState(m_iSubItem);

	AfxGetApp()->WriteProfileInt(_T("MessageView"), _T("SortSubItem"), m_iSubItem);
	AfxGetApp()->WriteProfileInt(_T("MessageView"), _T("SortState"), (UINT)m_ssDefault);

	CaplListView::OnDestroy();	
}

void CMailListView::OnShowDeletedMessages() 
{
	m_iShowDeletedMes=!m_iShowDeletedMes;
	UpdateView();
}

void CMailListView::OnUpdateShowDeletedMessages(CCmdUI* pCmdUI) 
{
	pCmdUI->SetCheck(m_iShowDeletedMes);
}

void CMailListView::OnShowLostMessages() 
{
	m_iShowLostMes=!m_iShowLostMes;
	UpdateView();
}

void CMailListView::OnUpdateShowLostMessages(CCmdUI* pCmdUI) 
{
	pCmdUI->SetCheck(m_iShowLostMes);
	pCmdUI->Enable(m_cur_item && m_cur_item->m_type==APL_TREE_ITEM_MESSAGEFOLDER);
}

void CMailListView::OnShowFolderMessages() 
{
	m_iShowFolderMes=!m_iShowFolderMes;
	UpdateView();
}

void CMailListView::OnUpdateShowFolderMessages(CCmdUI* pCmdUI) 
{
	pCmdUI->SetCheck(m_iShowFolderMes);
	pCmdUI->Enable(m_cur_item && m_cur_item->m_type==APL_TREE_ITEM_MESSAGEFOLDER);
}

