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

#include "PSMDoc.h"

#include "aplTopLevelItem.h"
#include "aplFolderTreeItem.h"
#include "aplMessageTreeItem.h"
#include "aplMessageFolderTreeItem.h"
#include "TabView.h"

#include "resource.h"

//CaplMessageFolderTreeItem
CaplMessageFolderTreeItem::CaplMessageFolderTreeItem(CTreeCtrl *tree, CPSMDoc *doc)
{
	m_type= APL_TREE_ITEM_MESSAGEFOLDER;
	m_doc= doc;
	m_tree= tree;
	m_bCanExpand= true;
	m_bWithLosted= false;
	if(doc!=0) 
		doc->m_items.Add(this);	
}

bool CaplMessageFolderTreeItem::GetName(CString &name)
{
	name= m_name;
	return true;
}
 
bool CaplMessageFolderTreeItem::RefreshItem()
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	
	UINT ico= ICON_MSG_INDEX;
	
	if(m_tree!=0)
	{
		CString name, buf, buf1;
		GetName(name);
		
		if(name== APL_T("Входящие")) ico=ICON_MESSAGES;
		else if(name== APL_T("Отправленные")) ico=ICON_MESSAGES+1;
		else if(name== APL_T("Черновики")) ico=ICON_MESSAGES+2;

		SetItemImage(ico, IDX_IL_TREE_ITEM);
		m_tree->SetItemText(m_item, name);
		
		Sort();
		m_tree->RedrawWindow();
	}
	if(m_doc->m_tab_view->m_item_old==this) m_doc->ChangeItem(this);
	return true;
}

bool CaplMessageFolderTreeItem::CreateTreeItem(HTREEITEM parent_item)
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	
	CString buf;
	GetName(buf);
	UINT ico= ICON_MSG_INDEX;
	
	if(buf== APL_T("Входящие")) ico=ICON_MESSAGES;
	else if(buf== APL_T("Отправленные")) ico=ICON_MESSAGES+1;
	else if(buf== APL_T("Черновики")) ico=ICON_MESSAGES+2;

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

	return true;
}

bool CaplMessageFolderTreeItem::Expand(UINT action)
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	
	if(action==2)
	{
//		if(m_hasSubItem)Expand(1);
		if(m_expanded) return true;
		
		if(m_fictive_item!=0)
		{
			m_tree->DeleteItem(m_fictive_item);
			m_fictive_item=0;
		}

		if(m_name== APL_T("Почта"))
		{
			CaplMessageFolderTreeItem *pIncFolder= new CaplMessageFolderTreeItem(
				m_tree, m_doc);
			pIncFolder->m_name=  APL_T("Входящие");
			pIncFolder->CreateTreeItem(m_item);
			m_doc->m_user_incoming_folder= (CaplTreeItem*)pIncFolder;

			CaplMessageFolderTreeItem *pSendFolder= new CaplMessageFolderTreeItem(
				m_tree, m_doc);
			pSendFolder->m_name=  APL_T("Отправленные");
			pSendFolder->CreateTreeItem(m_item);
			m_doc->m_user_sended_folder= (CaplTreeItem*)pSendFolder;
			
			CaplMessageFolderTreeItem *pDraftFolder= new CaplMessageFolderTreeItem(
				m_tree, m_doc);
			pDraftFolder->m_name=  APL_T("Черновики");
			pDraftFolder->CreateTreeItem(m_item);
			m_doc->m_user_drafted_folder= (CaplTreeItem*)pDraftFolder;
		}
		else 
		{
			InsertMessages(m_bWithLosted);
		}

		m_expanded= true;
	}
	else if(action==1)
	{
		if(m_bCanExpand)
		{
			m_tree->SetRedraw(FALSE);
			CaplMessageTreeItem::m_bShowInListCtrl= false;
			while(1)
			{
				HTREEITEM item1=m_tree->GetChildItem(m_item);
				if(item1==0) break;
				CaplTreeItem* tmpItem= (CaplTreeItem*)m_tree->GetItemData(item1);
				if(tmpItem==0) break;
				
				CaplMessageTreeItem *item= NULL;
				if(tmpItem->m_type==APL_TREE_ITEM_MESSAGE)
				{
					item= (CaplMessageTreeItem*)tmpItem;
				}
				else if(tmpItem->m_type==APL_TREE_ITEM_MESSAGEFOLDER)
				{
					//сворачивается Почта
					m_doc->m_incoming_messages.Clear();
					m_doc->m_send_or_dr_messages.Clear();
					
					m_doc->m_user_incoming_folder= NULL;
					m_doc->m_user_sended_folder= NULL;
					m_doc->m_user_drafted_folder= NULL;
				}
				
				if(item)
				{
					CaplInstance* mes= item->m_message;
					CString buf;
					GetName(buf);
					if(mes!=0 && buf== APL_T("Входящие")) 
						m_doc->m_incoming_messages.Remove(m_doc->m_incoming_messages.Find(mes));
					if(mes!=0 && (buf== APL_T("Отправленные") || buf== APL_T("Черновики"))) 
						m_doc->m_send_or_dr_messages.Remove(m_doc->m_send_or_dr_messages.Find(mes));
				}
				m_doc->m_items.Remove(m_doc->m_items.Find(tmpItem));
			}
 			if(!m_fictive_item)m_fictive_item=m_tree->InsertItem(_T("fictive"), 0, 0, m_item);
						
			CollapseItem();

			m_hasSubItem=false;
			m_expanded=false;
			CaplMessageTreeItem::m_bShowInListCtrl= true;
			m_tree->SetRedraw(TRUE);		
		}
	}	
	return true;
}

void CaplMessageFolderTreeItem::ShowProperties()
{
	
}

bool CaplMessageFolderTreeItem::ShowInListCtrl(CListCtrl *list)
{
//	CHECK_SHOW_LIST_CTRL(m_inst);

	return true;
}

void CaplMessageFolderTreeItem::ShowCmd(long cmd)
{
	
}
BOOL CaplMessageFolderTreeItem::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:
		pCmdUI->Enable(TRUE); return TRUE; break;
	}*/
	return FALSE;
}

bool CaplMessageFolderTreeItem::TrackPopupMenu(CWnd* wnd, CPoint &point, UINT view_mode)
{
	if(!m_doc || !m_doc->m_api.m_data.IsConnected()) return false;

	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_FOLDER_MENU);
    ASSERT(pPopup != NULL);
	if(pPopup==0) return false;

	UpdateMenu((CMenu**)&pPopup, view_mode);

	BOOL res = pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD,
						point.x, point.y, wnd);
	aplExtent ext;
	switch (res)
	{
		case ID_MESSAGE_DELIVER:
			{
				CString buf;
				for(int i= 0; i<m_doc->m_items.GetSize(); i++)
				{
					m_doc->m_items[i]->GetName(buf);
					if(buf== APL_T("Почта")) 
					{
						m_doc->m_items[i]->m_tree->Expand(
							m_doc->m_items[i]->m_tree->GetParentItem(m_doc->m_items[i]->m_item), 
							TVE_EXPAND);
						
						m_doc->m_items[i]->MyExpand();
						break;
					}
				}
			}

			if(!m_doc->m_user_incoming_folder->IsExpandet())
				m_doc->m_user_incoming_folder->MyExpand();
			else
				((CaplMessageFolderTreeItem*)m_doc->m_user_incoming_folder)->InsertMessages();

			break;
		case ID_NEW_MESSAGE_CREATE:
			{
				CaplMessageTreeItem::CreateMessage(m_doc, NULL, ext);
				break;
			}
		case ID_MESSAGE_OFFISIALE:
			{
				CString buf;
				for(int i= 0; i<m_doc->m_items.GetSize(); i++)
				{
					m_doc->m_items[i]->GetName(buf);
					if(buf== APL_T("Почта")) 
					{
						m_doc->m_items[i]->m_tree->Expand(
							m_doc->m_items[i]->m_tree->GetParentItem(m_doc->m_items[i]->m_item), 
							TVE_EXPAND);
						
						m_doc->m_items[i]->MyExpand();
						break;
					}
				}
				if(!m_doc->m_user_incoming_folder->IsExpandet())
				{
					((CaplMessageFolderTreeItem*)m_doc->m_user_incoming_folder)->m_bWithLosted= true;
					((CaplMessageFolderTreeItem*)m_doc->m_user_incoming_folder)->MyExpand();
					((CaplMessageFolderTreeItem*)m_doc->m_user_incoming_folder)->m_bWithLosted= false;
				}
				else
					((CaplMessageFolderTreeItem*)m_doc->m_user_incoming_folder)->InsertMessages(true);
				break;
			}
		default: PrepareContextMenu(res); 
			break;
	}
	return true;

}

int CALLBACK CaplMessageFolderTreeItem::CompareMesHtreeItem(LPARAM lParam1, LPARAM lParam2,LPARAM lParamSort)
{
	if(lParam1==0) return 0;
	if(lParam2==0) return 0;
	CTreeCtrl *tree=((CaplTreeItem*)lParam1)->m_tree;
	if(tree==0) return 0;
	HTREEITEM item1=((CaplTreeItem*)lParam1)->m_item;
	HTREEITEM item2=((CaplTreeItem*)lParam2)->m_item;
	
	if(((CaplTreeItem*)lParam1)->m_type!=APL_TREE_ITEM_MESSAGE || ((CaplTreeItem*)lParam2)->m_type!=APL_TREE_ITEM_MESSAGE)
		return CompareHtreeItem(lParam1, lParam2, lParamSort);

	CaplAPI* api = &((CaplTreeItem*)lParam2)->m_doc->m_api;
	
	CString date1, date2;

	CaplInstance *msg1=((CaplMessageTreeItem*)lParam1)->m_message;
	CaplInstance *msg2=((CaplMessageTreeItem*)lParam2)->m_message;

	if(0==msg1 || 0==msg2 ) return  0;
	if(0==msg1->GetType() || 0==msg2->GetType()) return  0;

	api->m_data.GetAttr(msg1, api->m_message_mgr.a_message_date_send, date1);
	api->m_data.GetAttr(msg2, api->m_message_mgr.a_message_date_send, date2);

	return (date2.Compare(date1));
}

void CaplMessageFolderTreeItem::Sort(bool bRefreshParent)
{
	if(m_tree==0) return;
	if(m_item==0) return;

	if(bRefreshParent)
	{
		if (m_tree->ItemHasChildren(m_item))
		{
		   HTREEITEM hChildItem = m_tree->GetChildItem(m_item);

		   while (hChildItem != NULL)
		   {
				CaplTreeItem *item=(CaplTreeItem*)m_tree->GetItemData(hChildItem);
				if(item!=0)item->RefreshItem();
				hChildItem = m_tree->GetNextItem(hChildItem, TVGN_NEXT);
		   }
		}
	}
	TVSORTCB sortcb;
	sortcb.hParent=m_item;
	sortcb.lpfnCompare=CompareMesHtreeItem;
	sortcb.lParam=1;
	m_tree->SortChildrenCB(&sortcb);
}

bool CaplMessageFolderTreeItem::InsertMessages(bool bWithLosted)
{
	if(!m_doc->m_api.m_data.IsConnected()) return false;

	m_bCanExpand= false;
	m_tree->SetRedraw(FALSE);

	aplExtent ext;
	aplExtent* sincExt;

	bool bCheckResDates= false;

	if(m_name== APL_T("Входящие"))
	{
		if(m_doc->m_api.m_message_mgr.GetPersonIncomingMessages(ext, m_doc->m_api.m_appr_mgr.GetCurrentPerson(), false, bWithLosted, false))
			AfxMessageBox( APL_T("Получены новые сообщения!"), MB_OK|MB_ICONINFORMATION);
		
		sincExt= &m_doc->m_incoming_messages;
		CaplMessageTreeItem::m_iNameFormate= APL_MESSAGE_INCOMING_FORMATE;
		bCheckResDates= true;
	}
	else if(m_name== APL_T("Отправленные"))
	{
		m_doc->m_api.m_message_mgr.GetPersonSendedMessages(ext, m_doc->m_api.m_appr_mgr.GetCurrentPerson(), false, false);
		sincExt= &m_doc->m_send_or_dr_messages;
		CaplMessageTreeItem::m_iNameFormate= APL_MESSAGE_SENDED_FORMATE;
	}
	else if(m_name== APL_T("Черновики"))
	{
		m_doc->m_api.m_message_mgr.GetPersonDraftedMessages(ext, m_doc->m_api.m_appr_mgr.GetCurrentPerson(), false);
		sincExt= &m_doc->m_send_or_dr_messages;
		CaplMessageTreeItem::m_iNameFormate= APL_MESSAGE_SENDED_FORMATE;
	}

	bool bIsNewMessageFound= false;
	CString buf;

	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(!sincExt || (-1!=sincExt->Find(ext[i]))) continue;
		
		if(bCheckResDates)
		{
			m_doc_data.GetAttr(ext[i], m_doc->m_api.m_message_mgr.a_message_date_received, buf);
			if(buf.IsEmpty() || buf== _T(" "))
			{
				bIsNewMessageFound= true;
				m_doc_data.PutAttr(ext[i], m_doc->m_api.m_message_mgr.a_message_date_received, sDate);
			}				
		}
			
		CaplMessageTreeItem *message_item= new CaplMessageTreeItem(m_tree, m_doc, ext[i]);
		message_item->CreateTreeItem(m_item);
		sincExt->Add(ext[i]);
	}

	CaplMessageTreeItem::m_iNameFormate= APL_MESSAGE_NON_FORMATE;
	m_tree->SetRedraw(TRUE);
	m_bCanExpand= true;
	m_expanded= true;
	m_hasSubItem= true;
	Sort();	

	return true;
}
