//this file is part of eMule
//Copyright (C)2002-2007 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include "emule.h"
#include "KademliaWnd.h"
#include "KadContactListCtrl.h"
#include "Ini2.h"
#include "OtherFunctions.h"
#include "emuledlg.h"

// X-Ray :: IP2Country :: Start
#include "MemDC.h"
#define DLC_DT_TEXT (DT_LEFT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS)
// X-Ray :: IP2Country :: End

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


// CONContactListCtrl

enum ECols
{
	// X-Ray :: IP2Country :: Start
	/*
	colID = 0,
	colID,
	colType,
	colDistance
	*/
	colIP = 0,
	colID,
	colType,
	colDistance,
	colCountry
	// X-Ray :: IP2Country :: End
};

IMPLEMENT_DYNAMIC(CKadContactListCtrl, CMuleListCtrl)

BEGIN_MESSAGE_MAP(CKadContactListCtrl, CMuleListCtrl)
	ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnColumnClick)
	ON_WM_DESTROY()
	ON_WM_SYSCOLORCHANGE()
END_MESSAGE_MAP()

CKadContactListCtrl::CKadContactListCtrl()
{
	SetGeneralPurposeFind(true);
	SetName(_T("ONContactListCtrl"));
}

CKadContactListCtrl::~CKadContactListCtrl()
{
}

void CKadContactListCtrl::Init()
{
	SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_INFOTIP);

	InsertColumn(colIP, GetResString(IDS_IP), LVCFMT_LEFT, 50); // X-Ray :: IP2Country
	InsertColumn(colID,GetResString(IDS_ID),LVCFMT_LEFT,100);
	InsertColumn(colType,GetResString(IDS_TYPE) ,LVCFMT_LEFT,50);
	InsertColumn(colDistance,GetResString(IDS_KADDISTANCE),LVCFMT_LEFT,50);
	InsertColumn(colCountry, GetResString(IDS_COUNTRY), LVCFMT_LEFT, 100); // X-Ray :: IP2Country

	SetAllIcons();
	Localize();

	LoadSettings();
	int iSortItem = GetSortItem();
	bool bSortAscending = GetSortAscending();

	SetSortArrow(iSortItem, bSortAscending);
	SortItems(SortProc, MAKELONG(iSortItem, (bSortAscending ? 0 : 0x0001)));
}

void CKadContactListCtrl::SaveAllSettings()
{
	SaveSettings();
}

void CKadContactListCtrl::OnSysColorChange()
{
	CMuleListCtrl::OnSysColorChange();
	SetAllIcons();
}

void CKadContactListCtrl::SetAllIcons()
{
	// X-Ray :: IP2Country :: Start
	/*
	CImageList iml;
	*/
	// X-Ray :: IP2Country :: End
	iml.Create(16,16,theApp.m_iDfltImageListColorFlags|ILC_MASK,0,1);
	iml.SetBkColor(CLR_NONE);
	iml.Add(CTempIconLoader(_T("Contact0")));
	iml.Add(CTempIconLoader(_T("Contact1")));
	iml.Add(CTempIconLoader(_T("Contact2")));
	iml.Add(CTempIconLoader(_T("Contact3")));
	iml.Add(CTempIconLoader(_T("Contact4")));
	// X-Ray :: IP2Country :: Start
	/*
	ASSERT( (GetStyle() & LVS_SHAREIMAGELISTS) == 0 );
	HIMAGELIST himl = ApplyImageList(iml.Detach());
	if (himl)
		ImageList_Destroy(himl);
	*/
	// X-Ray :: IP2Country :: End
}

void CKadContactListCtrl::Localize()
{
	CHeaderCtrl* pHeaderCtrl = GetHeaderCtrl();
	HDITEM hdi;
	hdi.mask = HDI_TEXT;
	CString strRes;

	for (int icol=0;icol< pHeaderCtrl->GetItemCount() ;icol++) 
	{
		switch (icol) 
		{
			case colIP: strRes = GetResString(IDS_IP); break; // X-Ray :: IP2Country
			case colID: strRes = GetResString(IDS_ID); break;
			case colType: strRes = GetResString(IDS_TYPE); break;
			case colDistance: strRes = GetResString(IDS_KADDISTANCE); break;
			case colCountry: strRes = GetResString(IDS_COUNTRY); break; // X-Ray :: IP2Country
		}
	
		hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
		pHeaderCtrl->SetItem(icol, &hdi);
	}

	int iItems = GetItemCount();
	for (int i = 0; i < iItems; i++)
		UpdateContact(i, (Kademlia::CContact*)GetItemData(i), true);
}
	
void CKadContactListCtrl::UpdateContact(int iItem, const Kademlia::CContact* contact, bool bLocalize)
{
	CString id;
	if (!bLocalize) // update the following fields only if really needed (it's quite expensive to always update them)
	{
		contact->GetClientID(&id);
		SetItemText(iItem,colID,id);

		id.Format(_T("%i(%u)"),contact->GetType(), contact->GetVersion());
		SetItemText(iItem,colType,id);

		contact->GetDistance(&id);
		SetItemText(iItem,colDistance,id);

		SetItem(iItem,0,LVIF_IMAGE,0,contact->GetType()>4?4:contact->GetType(),0,0,0,0);
	}
}

void CKadContactListCtrl::UpdateKadContactCount()
{
	CString id;
	id.Format(_T("%s (%i)"), GetResString(IDS_KADCONTACTLAB), GetItemCount());
	theApp.emuledlg->kademliawnd->GetDlgItem(IDC_KADCONTACTLAB)->SetWindowText(id);
}

bool CKadContactListCtrl::ContactAdd(const Kademlia::CContact* contact)
{
	bool bResult = false;
	try
	{
		ASSERT( contact != NULL );
		int iItem = InsertItem(LVIF_TEXT|LVIF_PARAM,GetItemCount(),NULL,0,0,0,(LPARAM)contact);
		if (iItem >= 0)
		{
			bResult = true;
	//		Trying to update all the columns causes one of the connection freezes in win98
	//		ContactRef(contact);
			// If it still doesn't work under Win98, uncomment the '!afxData.bWin95' term
			if (!afxData.bWin95 && iItem >= 0)
				UpdateContact(iItem, contact);
			UpdateKadContactCount();
		}
	}
	catch(...){ASSERT(0);}
	return bResult;
}

void CKadContactListCtrl::ContactRem(const Kademlia::CContact* contact)
{
	try
	{
		ASSERT( contact != NULL );
		LVFINDINFO find;
		find.flags = LVFI_PARAM;
		find.lParam = (LPARAM)contact;
		int iItem = FindItem(&find);
		if (iItem != -1)
		{
			DeleteItem(iItem);
			UpdateKadContactCount();
		}
	}
	catch(...){ASSERT(0);}
}

void CKadContactListCtrl::ContactRef(const Kademlia::CContact* contact)
{
	try
	{
		ASSERT( contact != NULL );
		LVFINDINFO find;
		find.flags = LVFI_PARAM;
		find.lParam = (LPARAM)contact;
		int iItem = FindItem(&find);
		if (iItem != -1)
			UpdateContact(iItem, contact);
	}
	catch(...){ASSERT(0);}
}

BOOL CKadContactListCtrl::OnCommand(WPARAM /*wParam*/, LPARAM /*lParam*/)
{
	// ???
	return TRUE;
}

void CKadContactListCtrl::OnColumnClick(NMHDR* pNMHDR, LRESULT* pResult)
{
	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;

	// Determine ascending based on whether already sorted on this column
	int iSortItem = GetSortItem();
	bool bOldSortAscending = GetSortAscending();
	bool bSortAscending = (iSortItem != pNMListView->iSubItem) ? true : !bOldSortAscending;

	// Item is column clicked
	iSortItem = pNMListView->iSubItem;

	// Sort table
	UpdateSortHistory(MAKELONG(iSortItem, (bSortAscending ? 0 : 0x0001)));
	SetSortArrow(iSortItem, bSortAscending);
	SortItems(SortProc, MAKELONG(iSortItem, (bSortAscending ? 0 : 0x0001)));

	*pResult = 0;
}

int CKadContactListCtrl::SortProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
	Kademlia::CContact* item1 = (Kademlia::CContact*)lParam1;
	Kademlia::CContact* item2 = (Kademlia::CContact*)lParam2; 
	if((item1 == NULL) || (item2 == NULL))
		return 0;

	int iResult;
	switch(LOWORD(lParamSort))
	{
		// X-Ray :: IP2Country :: Start
		case colIP:
		{
			UINT uIP1 = htonl(item1->GetIP());
			UINT uIP2 = htonl(item2->GetIP());
			if (uIP1 < uIP2)
				iResult = -1;
			else if (uIP1 > uIP2)
				iResult = 1;
			else 
				iResult = 0;
			break;
		}
		// X-Ray :: IP2Country :: End
		case colID:
		{
			Kademlia::CUInt128 i1;
			Kademlia::CUInt128 i2;
			item1->GetClientID(&i1);
			item2->GetClientID(&i2);
			iResult = i1.CompareTo(i2);
			break;
		}
		case colType:
			iResult = item1->GetType() - item2->GetType();
			break;
		case colDistance:
		{
			Kademlia::CUInt128 distance1, distance2;
			item1->GetDistance(&distance1);
			item2->GetDistance(&distance2);
			iResult = distance1.CompareTo(distance2);
			break;
		}
		// X-Ray :: IP2Country :: Start
		case colCountry:
		{
			CString strCountry1 = item1->GetCountryName();
			CString strCountry2 = item2->GetCountryName();
			if (!strCountry1.IsEmpty() && !strCountry2.IsEmpty())
				iResult = CompareLocaleStringNoCase(strCountry1, strCountry2);
			else
				iResult = strCountry1.IsEmpty() ? (strCountry2.IsEmpty()?0:1) : -1;
			break;
		}
		// X-Ray :: IP2Country :: End
		default:
			return 0;
	}
	if (HIWORD(lParamSort))
		iResult = -iResult;
	return iResult;
}

// X-Ray :: IP2Country :: Start
void CKadContactListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	if( !theApp.emuledlg->IsRunning() )
		return;
	if (!lpDrawItemStruct->itemData)
		return;
	CDC* odc = CDC::FromHandle(lpDrawItemStruct->hDC);
	BOOL bCtrlFocused = ((GetFocus() == this ) || (GetStyle() & LVS_SHOWSELALWAYS));
	if (lpDrawItemStruct->itemState & ODS_SELECTED)
	{
		if(bCtrlFocused)
			odc->SetBkColor(m_crHighlight);
		else
			odc->SetBkColor(m_crNoHighlight);
	}
	else
		odc->SetBkColor(GetBkColor());
	Kademlia::CContact* contact = (Kademlia::CContact*)lpDrawItemStruct->itemData;
	CMemDC dc(odc, &lpDrawItemStruct->rcItem);
	CFont* pOldFont = dc.SelectObject(GetFont());
		CRect cur_rec(lpDrawItemStruct->rcItem);
	COLORREF crOldTextColor = dc.SetTextColor((lpDrawItemStruct->itemState & ODS_SELECTED) ? m_crHighlightText : m_crWindowText);

	int iOldBkMode;
	if (m_crWindowTextBk == CLR_NONE){
		DefWindowProc(WM_ERASEBKGND, (WPARAM)(HDC)dc, 0);
		iOldBkMode = dc.SetBkMode(TRANSPARENT);
	}
	else
		iOldBkMode = OPAQUE;

	CString sBuffer;
	CHeaderCtrl *pHeaderCtrl = GetHeaderCtrl();
	int iCount = pHeaderCtrl->GetItemCount();
	cur_rec.right = cur_rec.left - 8;
	cur_rec.left += 4;

	for(int iCurrent = 0; iCurrent < iCount; iCurrent++)
	{
		int iColumn = pHeaderCtrl->OrderToIndex(iCurrent);
		if( !IsColumnHidden(iColumn) )
		{
			cur_rec.right += GetColumnWidth(iColumn);
			switch(iColumn)
			{
				case colIP:
					{
						sBuffer = ipstr(contact->GetIP());
						uint8 morespace = 0;
						if(theApp.ip2country->ShowCountryFlag()){
							POINT point = {cur_rec.left,cur_rec.top+1};
							cur_rec.left+=20;
							morespace += 20;
							theApp.ip2country->GetFlagImageList()->Draw(dc, contact->GetCountryFlagIndex(), point, ILD_NORMAL);
						}
						dc.DrawText(sBuffer,sBuffer.GetLength(),&cur_rec, DLC_DT_TEXT);
						cur_rec.left -= morespace;
						break;
					}
				case colID:
					{
						POINT point = {cur_rec.left, cur_rec.top};
						iml.Draw(dc, contact->GetType(), point, ILD_NORMAL); 

						cur_rec.left +=20;
						contact->GetClientID(&sBuffer);
						break;
					}
				case colType:
					sBuffer.Format(_T("%i"),contact->GetType());
					break;
				case colDistance:
					contact->GetDistance(&sBuffer);
					break;
				case colCountry:
					sBuffer = contact->GetCountryName();
					break;
			}
			if(iColumn != colIP )
				dc.DrawText(sBuffer,sBuffer.GetLength(),&cur_rec, DLC_DT_TEXT);
			if( iColumn == colID )
				cur_rec.left -= 20;
			cur_rec.left += GetColumnWidth(iColumn);
		}
	}
	//draw rectangle around selected item(s)
	if (lpDrawItemStruct->itemState & ODS_SELECTED)
	{
		RECT outline_rec = lpDrawItemStruct->rcItem;
		outline_rec.top--;
		outline_rec.bottom++;
		dc.FrameRect(&outline_rec, &CBrush(GetBkColor()));
		outline_rec.top++;
		outline_rec.bottom--;
		outline_rec.left++;
		outline_rec.right--;
		if(bCtrlFocused)
			dc.FrameRect(&outline_rec, &CBrush(m_crFocusLine));
		else
			dc.FrameRect(&outline_rec, &CBrush(m_crNoFocusLine));
	}
	if (m_crWindowTextBk == CLR_NONE)
		dc.SetBkMode(iOldBkMode);
	dc.SelectObject(pOldFont);
	dc.SetTextColor(crOldTextColor);
}
// X-Ray :: IP2Country :: End