// aplListView.cpp : implementation file
//

#include "stdafx.h"
#include "resource.h"
#include "psm.h"
#include "aplTreeItem.h"
#include "aplMessageFolderTreeItem.h"
#include "aplFolderTreeItem.h"
#include "aplListView.h"
#include "MailListView.h"
#include <aplStepManager.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/*
int CALLBACK CompareListItems(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
	int nIndex=-1;
	CString sStr1, sStr2;
	CaplListView * pView = (CaplListView *)lParamSort;
	if(pView==0) return 0;
	bool sort_type=pView->m_sort_type;
	
	nIndex=pView->GetItemByData((int)lParam1);
	sStr1 = pView->GetListCtrl().GetItemText(nIndex, pView->m_sort_column);
	nIndex=pView->GetItemByData((int)lParam2);
	sStr2 = pView->GetListCtrl().GetItemText(nIndex, pView->m_sort_column);
	if (sStr1 == sStr2)
		return 0;
	if (sStr1 > sStr2)
	{
		if (sort_type)
			return 1;
		else
			return -1;
	}
	else
	{
		if (sort_type)
			return -1;
		else
			return 1;
	}
}
*/
/////////////////////////////////////////////////////////////////////////////
// CaplListView

IMPLEMENT_DYNCREATE(CaplListView, CMultiColumnSortListView)

CaplListView::CaplListView()
{
	m_cur_item=0;
}

CaplListView::~CaplListView()
{
}


BEGIN_MESSAGE_MAP(CaplListView, CMultiColumnSortListView)
	//{{AFX_MSG_MAP(CaplListView)
	ON_WM_CONTEXTMENU()
	//}}AFX_MSG_MAP
	ON_WM_LBUTTONDBLCLK()
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CaplListView drawing

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

/////////////////////////////////////////////////////////////////////////////
// CaplListView diagnostics

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

void CaplListView::Dump(CDumpContext& dc) const
{
	CListView::Dump(dc);
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CaplListView message handlers
void CaplListView::UpdateTreeItem(CaplTreeItem *item){};


int CaplListView::GetItemByData(long data)
{
	int k,i=-1;
	while(1)
	{
		i=LIST.GetNextItem(i,LVNI_ALL);
		if(i==-1) break;
		k=LIST.GetItemData(i);
		if(k==data) return i;
	}
	return -1;
}

void CaplListView::OnContextMenu(CWnd* pWnd, CPoint point) 
{
	CMenu menu;  gSetPsmResourceHandle();
	VERIFY(menu.LoadMenu(IDR_LIST_CONTEXT_MENU));
// 	VERIFY(menu.LoadToolBar(IDR_MENU_ICONS));
	CaplMenu::Install(this); // 	VERIFY(CaplMenu::Install(pWnd, ePopupMenu ));

	int indexSubmenu=0;
	CString name_appended;
	bool use_mail_menu = false;
	bool is_recipi = false;
	bool is_sender = false;
	bool is_draft;
	bool update_item = false;
	int insert_menu_pos = 3;
	int count_selected = 0;

	if(IsKindOf(RUNTIME_CLASS(CMailListView)))
	{
		indexSubmenu=1;
		((CMailListView*)this)->GetStateAdd2AddressBook(is_recipi, is_sender);
		use_mail_menu =  ((CMailListView*)this)->CheckMailMenu(is_draft);
	}

    CMenu* pPopup = menu.GetSubMenu(indexSubmenu);
    ASSERT(pPopup != NULL);
	if(pPopup==0) return;

	if(use_mail_menu)
	{
		int num_curr= GetListCtrl().GetNextItem( -1 , LVNI_ALL | LVNI_SELECTED );
		while( num_curr!= -1){
			count_selected++;
			num_curr= GetListCtrl().GetNextItem( num_curr , LVNI_ALL | LVNI_SELECTED );
		}
		if(count_selected==0 || count_selected > 1)
		{
			pPopup->EnableMenuItem(ID_MES_PROPERTIES,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_MESSAGE_REPLY,MF_BYCOMMAND|MF_GRAYED);
			pPopup->EnableMenuItem(ID_MESSAGE_FORWARD,MF_BYCOMMAND|MF_GRAYED);
		}

		pPopup->InsertMenu(insert_menu_pos++,MF_BYPOSITION|MF_SEPARATOR,0,_T(""));
		
		if(is_recipi)pPopup->InsertMenu(insert_menu_pos++,MF_BYPOSITION|MF_STRING,ID_ADD2ADDRESS_BOOK_RECIPI,S::message_add2address_recipient());
		else pPopup->InsertMenu(insert_menu_pos++,MF_BYPOSITION|MF_STRING|MF_GRAYED,ID_ADD2ADDRESS_BOOK_RECIPI,S::message_add2address_recipient());

		if(is_sender)pPopup->InsertMenu(insert_menu_pos++,MF_BYPOSITION|MF_STRING,ID_ADD2ADDRESS_BOOK_SENDER,S::message_add2address_sender());
		else pPopup->InsertMenu(insert_menu_pos++,MF_BYPOSITION|MF_STRING|MF_GRAYED,ID_ADD2ADDRESS_BOOK_SENDER,S::message_add2address_sender());

		//if(m_cur_item->m_name!=APL_T("Черновики"))
		pPopup->InsertMenu(insert_menu_pos++,MF_BYPOSITION|MF_SEPARATOR,0,_T(""));
		if(m_cur_item->m_type==_T("Folder"))
			pPopup->InsertMenu(insert_menu_pos++,MF_BYPOSITION|MF_STRING,ID_COPY_MAIL2FOLDER,S::message_remove_from_folder());
		else if(m_cur_item->m_type==_T("MessageFolder"))
		{	
			if(is_draft)
				pPopup->InsertMenu(insert_menu_pos++,MF_BYPOSITION|MF_STRING|MF_GRAYED,ID_COPY_MAIL2FOLDER,S::message_move2folder());
			else
				pPopup->InsertMenu(insert_menu_pos++,MF_BYPOSITION|MF_STRING,ID_COPY_MAIL2FOLDER,S::message_move2folder());
		}

		CMenu* recivers_menu = new CMenu;
		recivers_menu->CreateMenu();
		//pSubMenu->InsertODMenu(iPos, name, MF_BYPOSITION|MF_POPUP,(UINT)found_menu->m_hMenu,-1);
		pPopup->InsertMenu(insert_menu_pos++, MF_BYPOSITION|MF_POPUP,(UINT)recivers_menu->m_hMenu,APL_T("Удалить"));
		recivers_menu->InsertMenu(0,MF_BYPOSITION|MF_POPUP,ID_DELETE,APL_T("Удалить"));
	}
	else
	{
		pPopup->EnableMenuItem(ID_MES_PROPERTIES,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_MESSAGE_REPLY,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_MESSAGE_FORWARD,MF_BYCOMMAND|MF_GRAYED);
	}

	POINT localpoint=point;
	ScreenToClient(&localpoint);

	int item=LIST.HitTest(localpoint); 


	if(!ShowProterties(true,item) ) pPopup->EnableMenuItem(ID_SHOW_PROPERTIES,MF_BYCOMMAND|MF_GRAYED);


	BOOL res=pPopup->TrackPopupMenu(TPM_LEFTALIGN|
		TPM_RIGHTBUTTON|TPM_RETURNCMD,point.x, point.y,pWnd);
	switch(res)
	{
	case ID_FILE_SAVE:
		{
			CString buf;
			if(m_cur_item!=0) m_cur_item->GetName(buf);
			apl_SaveListCtrlToFile(&GetListCtrl(),buf,buf);
		
		} break;

	case ID_EDIT_COPY_CELL_NUMBER:
	case ID_EDIT_COPY_CELL_ADDR:
	case ID_EDIT_COPY_CELL:
		{
			CString text;
			LIST.ScreenToClient(&point);
			LVHITTESTINFO HitTestInfo;
			HitTestInfo.pt=point;
			HitTestInfo.flags=0;//LVHT_ONITEMLABEL|LVHT_ONITEMICON;
			HitTestInfo.iItem=-1;
			HitTestInfo.iSubItem=-1;
			LIST.SubItemHitTest(&HitTestInfo); 
			if(HitTestInfo.iItem>=0)
			{
				if(HitTestInfo.iSubItem<0 )HitTestInfo.iSubItem=0;
				text=LIST.GetItemText(HitTestInfo.iItem,HitTestInfo.iSubItem);
			}
			if(text!=_T(""))
			{
				if(ID_EDIT_COPY_CELL_NUMBER==res)
				{
					text.TrimLeft();
					CString buf;
					int i=0;
					bool isNum=false;
					while(true)
					{
						TCHAR c=text[i];
						if(c==_T('\0')) break;
						if( (c>=_T('0') && c<=_T('9')) ||  (c>=_T('a') && c<=_T('f')) || (c>=_T('A') && c<=_T('F')) ) {buf+=c; isNum=true;}
						else
						{
							if(isNum) break; // Число кончилось
						}
						i++;
					}
					if(buf==_T("")) {text=_T(""); AfxMessageBox(APL_T("В строке число не найдено!"),MB_ICONWARNING);}
					else text=buf;
				}
				else if(ID_EDIT_COPY_CELL_ADDR==res)
				{
					int i=text.Find(_T("0x"));
					if(i<0) {text=_T(""); AfxMessageBox(APL_T("В строке не найден адрес (подстрока с '0x')!"),MB_ICONWARNING);}
					else
					{
						CString buf=_T("0x");
						i+=2;
						while(true)
						{
							TCHAR c=text[i];
							if( (c>=_T('0') && c<=_T('9')) ||  (c>=_T('a') && c<=_T('f')) || (c>=_T('A') && c<=_T('F')) ) buf+=c;
							else break;
							
							i++;
						}
						if(buf.GetLength()>2) text=buf;
						else text=_T("");
					}
				}
				if(text!=_T(""))
				{
					COleDataSource*	pSource = new COleDataSource();
					if(pSource==0) return;
					HGLOBAL hMem;

					hMem=GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE|GMEM_ZEROINIT,(text.GetLength()+1)*sizeof(TCHAR));
					if (!hMem) return;
					TCHAR *xxx=(TCHAR*)GlobalLock(hMem);
					memcpy(xxx,LPCTSTR(text),(text.GetLength()+1)*sizeof(TCHAR));		
					GlobalUnlock(hMem);

					#ifdef _UNICODE
						CLIPFORMAT text_format=CF_UNICODETEXT;
					#else
						CLIPFORMAT text_format=CF_TEXT;
					#endif

					pSource->CacheGlobalData(text_format, hMem);
					pSource->SetClipboard();
				}
			}

		}	break;
	case ID_EDIT_COPY:
		 {
			 COleDataSource*	pSource = new COleDataSource();
			 if(pSource==0) return;
			 HGLOBAL hMem;
			 
 			 CString text,text1;
			 text.Empty();
			 LIST.ScreenToClient(&point);
			 int line=LIST.HitTest(point); 
			 CHeaderCtrl* hc=LIST.GetHeaderCtrl();
			 if(hc==0)return;
			 int col_max=hc->GetItemCount();

			 TCHAR buf[256];
			 HDITEM HeaderItem;
			 HeaderItem.mask = HDI_TEXT;
			 HeaderItem.pszText = buf;
			 HeaderItem.cchTextMax = 256;

			 for(int col=0;col<col_max;col++){
				if(col!=0){text+=_T("; ");}
				hc->GetItem(col, &HeaderItem);
				text += buf;
				text +=_T(": ");
				text1=LIST.GetItemText(line,col);
				text+=text1.IsEmpty()?_T("?"):text1;
			 }

 			 hMem=GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE|GMEM_ZEROINIT,(text.GetLength()+1)*sizeof(TCHAR));
 			 if (!hMem) return;
 			 TCHAR *xxx=(TCHAR*)GlobalLock(hMem);
 			 memcpy(xxx,LPCTSTR(text),(text.GetLength()+1)*sizeof(TCHAR));		
 			 GlobalUnlock(hMem);
			#ifdef _UNICODE
				CLIPFORMAT text_format=CF_UNICODETEXT;
			#else
				CLIPFORMAT text_format=CF_TEXT;
			#endif
 			 pSource->CacheGlobalData(text_format, hMem);
			 pSource->SetClipboard();

		 }break;

	case ID_MES_PROPERTIES:
		if(IsKindOf(RUNTIME_CLASS(CMailListView))) ((CMailListView*)this)->OnMessageRead();
		break;
	case ID_MESSAGE_REPLY:
		{
			if(IsKindOf(RUNTIME_CLASS(CMailListView))) ((CMailListView*)this)->OnMessageReply();
			break;
		}
	case ID_MESSAGE_FORWARD:
		{
			if(IsKindOf(RUNTIME_CLASS(CMailListView))) ((CMailListView*)this)->OnMessageForward();
			break;
		}
	case ID_ADD2ADDRESS_BOOK_RECIPI:
	case ID_ADD2ADDRESS_BOOK_SENDER:
		((CMailListView*)this)->Add2AddressBook(res);
		break;
	case ID_COPY_MAIL2FOLDER:
		((CMailListView*)this)->Move2FromFolder(m_cur_item->m_type!=_T("Folder"));
		update_item = true;
		break;
	case ID_DELETE:
		((CMailListView*)this)->DeleteMessages();
		update_item = true;
		break;
	case ID_SHOW_PROPERTIES:
		{
			LIST.ScreenToClient(&point);
			int line=LIST.HitTest(point); 
			if(line>=0) ShowProterties(false,line);
		} break;

	//default: PrepareContextMenu(res); 
	}
	if(update_item && m_cur_item!=0)
	{
		if(m_cur_item->m_type == _T("Folder"))
		{
			((CaplFolderTreeItem*)m_cur_item)->ShowContents();
		}
	}
}

bool CaplListView::ShowProterties(bool bTest, int item)
{
	if(item<0) return false;
	CaplInstance *inst=(CaplInstance *)LIST.GetItemData(item);
	if(0==inst) return false;

	if(bTest) return true;

	CPSMDoc *m_doc = (CPSMDoc*)GetDocument();
	if(0==m_doc) return false;


	if(m_doc->m_api.m_data.IsKindOf(inst,m_doc->m_api.m_appr_mgr.e_person))
	{
		m_doc->m_api.m_appr_mgr.ShowPersonProperties(inst);
		return true;
	}
	return false;
}  

void CaplListView::OnLButtonDblClk(UINT nFlags, CPoint point)
{
	CMultiColumnSortListView::OnLButtonDblClk(nFlags, point);

	int i=LIST.HitTest(point); 
	if(i<0) return;

	CaplInstance *inst=(CaplInstance *)LIST.GetItemData(i);
	if(0==inst) return;

	CPSMDoc *m_doc = (CPSMDoc*)GetDocument();
	if(0==m_doc) return;

	if(m_doc->m_api.m_data.IsKindOf(inst,m_doc->m_api.m_appr_mgr.e_person))
	{
		m_doc->m_api.m_appr_mgr.ShowPersonProperties(inst);
		return;
	}

}
