//this file is part of eMule
//Copyright (C)2002 Merkur ( merkur-@users.sourceforge.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.

// UploadListCtrl.cpp : implementation file
//

#include "stdafx.h"
#include "emule.h"
#include "UploadListCtrl.h"
#include "otherfunctions.h"
#include "opcodes.h"
#include "ClientDetailDialog.h"

// CUploadListCtrl

IMPLEMENT_DYNAMIC(CUploadListCtrl, CMuleListCtrl)
CUploadListCtrl::CUploadListCtrl(){
	memset(&asc_sort, 0, sizeof(asc_sort)); // i_a 
}

void CUploadListCtrl::Init(){
	SetExtendedStyle(LVS_EX_FULLROWSELECT);
	InsertColumn(0,GetResString(IDS_QL_USERNAME),LVCFMT_LEFT,150,0);
	InsertColumn(1,GetResString(IDS_FILE),LVCFMT_LEFT,275,1);
	InsertColumn(2,GetResString(IDS_DL_SPEED),LVCFMT_LEFT,60,2);
	InsertColumn(3,GetResString(IDS_DL_TRANSF),LVCFMT_LEFT,65,3);
	InsertColumn(4,GetResString(IDS_WAITED),LVCFMT_LEFT,60,4);
	InsertColumn(5,GetResString(IDS_UPLOADTIME),LVCFMT_LEFT,60,6);
	InsertColumn(6,GetResString(IDS_STATUS),LVCFMT_LEFT,110,5);
	InsertColumn(7,IDS_COMPRESSION,LVCFMT_LEFT,110,7); // Add show compression
	imagelist.Create(16,16,ILC_COLOR32 | ILC_MASK,0,18);
	imagelist.SetBkColor(RGB(255,255,255));
	imagelist.Add(theApp.LoadIcon(IDI_USER0));
	imagelist.Add(theApp.LoadIcon(IDI_COMPPROT));
	imagelist.Add(theApp.LoadIcon(IDI_PLUS));
	imagelist.Add(theApp.LoadIcon(IDI_PLUSCOMPROT));
	imagelist.Add(theApp.LoadIcon(IDI_FRIEND));
	imagelist.Add(theApp.LoadIcon(IDI_MLDONK));
	imagelist.Add(theApp.LoadIcon(IDI_PLUSMLDONK));

	imagelist.Add(theApp.LoadIcon(IDI_TAROD)); // Added by Tarod
	imagelist.Add(theApp.LoadIcon(IDI_TARODPLUS)); // Added by Tarod

	SetImageList(&imagelist,LVSIL_SMALL);
	LoadSettings(CPreferences::tableUpload);

	// Barry - Use preferred sort order from preferences
	int sortItem = theApp.glob_prefs->GetColumnSortItem(CPreferences::tableUpload);
	bool sortAscending = theApp.glob_prefs->GetColumnSortAscending(CPreferences::tableUpload);
	SetSortArrow(sortItem, sortAscending);
	SortItems(SortProc, sortItem + (sortAscending ? 0:10));
}

CUploadListCtrl::~CUploadListCtrl(){
}

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

	strRes = GetResString(IDS_QL_USERNAME);
	hdi.pszText = strRes.GetBuffer();
	pHeaderCtrl->SetItem(0, &hdi);
	strRes.ReleaseBuffer();

	strRes = GetResString(IDS_FILE);
	hdi.pszText = strRes.GetBuffer();
	pHeaderCtrl->SetItem(1, &hdi);
	strRes.ReleaseBuffer();

	strRes = GetResString(IDS_DL_SPEED);
	hdi.pszText = strRes.GetBuffer();
	pHeaderCtrl->SetItem(2, &hdi);
	strRes.ReleaseBuffer();

	strRes = GetResString(IDS_DL_TRANSF);
	hdi.pszText = strRes.GetBuffer();
	pHeaderCtrl->SetItem(3, &hdi);
	strRes.ReleaseBuffer();

	strRes = GetResString(IDS_WAITED);
	hdi.pszText = strRes.GetBuffer();
	pHeaderCtrl->SetItem(4, &hdi);
	strRes.ReleaseBuffer();

	strRes = GetResString(IDS_UPLOADTIME);
	hdi.pszText = strRes.GetBuffer();
	pHeaderCtrl->SetItem(5, &hdi);
	strRes.ReleaseBuffer();

	strRes = GetResString(IDS_STATUS);
	hdi.pszText = strRes.GetBuffer();
	pHeaderCtrl->SetItem(6, &hdi);
	strRes.ReleaseBuffer();

	strRes = IDS_COMPRESSION;
	hdi.pszText = strRes.GetBuffer();
	pHeaderCtrl->SetItem(7, &hdi);
	strRes.ReleaseBuffer();
}

void CUploadListCtrl::AddClient(CUpDownClient* client){
	uint32 itemnr = GetItemCount();
	itemnr = InsertItem(LVIF_TEXT|LVIF_PARAM,itemnr,client->GetUserName(),0,0,1,(LPARAM)client);
	RefreshClient(client);
}

void CUploadListCtrl::RemoveClient(CUpDownClient* client){
	LVFINDINFO find;
	find.flags = LVFI_PARAM;
	find.lParam = (LPARAM)client;
	sint32 result = FindItem(&find);
	if (result != (-1) )
		DeleteItem(result);
}

void CUploadListCtrl::RefreshClient(CUpDownClient* client){
	LVFINDINFO find;
	find.flags = LVFI_PARAM;
	find.lParam = (LPARAM)client;
	sint32 itemnr = FindItem(&find);
	if (itemnr == (-1))
		return;
	uint8 image;
	if (client->IsFriend())
		image = 4;
	else if (client->ExtProtocolAvailable()){
		if (client->credits->GetScoreRatio() > 1)
			if (client->IsTarodVersion()) image = 8; else image = 3;
		else
			if (client->IsTarodVersion()) image = 7; else image = 1;
	}
	else{
		if (client->GetClientSoft() == SO_MLDONKEY ){
			if (client->credits->GetScoreRatio() > 1)
				image = 6;
			else
				image = 5;
		}
		else{
			if (client->credits->GetScoreRatio() > 1)
				image = 2;
			else
				image = 0;
		}
	}
	SetItem(itemnr,0,LVIF_IMAGE,0,image,0,0,0,0);
	char buffer[100];
	CKnownFile* file = theApp.sharedfiles->GetFileByID(client->reqfileid);
	if (file)
		SetItemText(itemnr,1,file->GetFileName());
	else
		SetItemText(itemnr,1,"?");
	sprintf(buffer,"%.1f kB/s",(float)client->GetDatarate()/1024);
	SetItemText(itemnr,2,buffer);
	CastItoXBytes(client->GetTransferedUp(),buffer);
	SetItemText(itemnr,3,buffer);
	CastSecondsToHM((client->GetWaitTime())/1000, buffer);
	SetItemText(itemnr,4,buffer);
	CastSecondsToHM((client->GetUpStartTimeDelay())/1000, buffer);
	SetItemText(itemnr,5,buffer);
	CString status;
	switch (client->GetUploadState()){
		case US_CONNECTING:
			status = GetResString(IDS_CONNECTING);
			break;
		case US_WAITCALLBACK:
			status = GetResString(IDS_CONNVIASERVER);
			break;
		case US_UPLOADING:
			status = GetResString(IDS_TRANSFERRING);
			break;
		default:
			status = GetResString(IDS_UNKNOWN);
	}
	SetItemText(itemnr,6,status);
	
	float compress = client->GetCompression() ;
	if (compress < 0.1f) {
		sprintf(buffer, "-", compress) ;
	} else {
		sprintf(buffer, "%.1f%%", compress);// Add show compression
		SetItemText(itemnr,7,buffer); // Add show compression
	}
}

BEGIN_MESSAGE_MAP(CUploadListCtrl, CMuleListCtrl)
	ON_NOTIFY_REFLECT (NM_RCLICK, OnNMRclick)
	ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnColumnClick)

END_MESSAGE_MAP()



// CUploadListCtrl message handlers
void CUploadListCtrl::OnNMRclick(NMHDR *pNMHDR, LRESULT *pResult){	
	POINT point;
	::GetCursorPos(&point);	

	if (m_ClientMenu) m_ClientMenu.DestroyMenu();
	m_ClientMenu.CreatePopupMenu();
	m_ClientMenu.AddMenuTitle(GetResString(IDS_CLIENTS));
	m_ClientMenu.AppendMenu(MF_STRING,MP_DETAIL, GetResString(IDS_SHOWDETAILS));
	m_ClientMenu.AppendMenu(MF_STRING,MP_ADDFRIEND, GetResString(IDS_ADDFRIEND));
	m_ClientMenu.AppendMenu(MF_STRING,MP_MESSAGE, GetResString(IDS_SEND_MSG));
	m_ClientMenu.AppendMenu(MF_STRING,MP_SHOWLIST, GetResString(IDS_VIEWFILES));
	m_ClientMenu.AppendMenu(MF_SEPARATOR);
	m_ClientMenu.AppendMenu(MF_STRING,MP_SWITCHCTRL, GetResString(IDS_VIEWQUEUE));
	
	SetMenu(&m_ClientMenu);
	m_ClientMenu.TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, point.x, point.y, this);
	*pResult = 0;
	m_ClientMenu.DestroyMenu();
}

BOOL CUploadListCtrl::OnCommand(WPARAM wParam,LPARAM lParam ){
	if (GetSelectionMark() != (-1)){
		CUpDownClient* client = (CUpDownClient*)GetItemData(GetSelectionMark());
		switch (wParam){
			case MP_SHOWLIST:
				client->RequestSharedFileList();
				break;
			case MP_MESSAGE:{
				theApp.emuledlg->chatwnd.StartSession(client);
				break;
			}
			case MP_ADDFRIEND:{
				theApp.friendlist->AddFriend(client);
				break;
			}
			case MP_DETAIL:
				CClientDetailDialog dialog(client);
				dialog.DoModal();
				break;

		}
	}
	switch(wParam){
		case MP_SWITCHCTRL:{
			((CTransferWnd*)GetParent())->SwitchUploadList();
		}

	}
	return true;
}


void CUploadListCtrl::OnColumnClick( NMHDR* pNMHDR, LRESULT* pResult){

	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
	// if it's a second click on the same column then reverse the sort order,
	// otherwise sort the new column in ascending order.
//	asc_sort[pNMListView->iSubItem] = !asc_sort[pNMListView->iSubItem];
//	SetSortArrow(pNMListView->iSubItem, asc_sort[pNMListView->iSubItem]);
//	SortItems(&SortProc,pNMListView->iSubItem+ ((asc_sort[pNMListView->iSubItem])? 0:10));

	// Barry - Store sort order in preferences
	// Determine ascending based on whether already sorted on this column
	int sortItem = theApp.glob_prefs->GetColumnSortItem(CPreferences::tableUpload);
	bool m_oldSortAscending = theApp.glob_prefs->GetColumnSortAscending(CPreferences::tableUpload);
	bool sortAscending = (sortItem != pNMListView->iSubItem) ? true : !m_oldSortAscending;
	// Item is column clicked
	sortItem = pNMListView->iSubItem;
	// Save new preferences
	theApp.glob_prefs->SetColumnSortItem(CPreferences::tableUpload, sortItem);
	theApp.glob_prefs->SetColumnSortAscending(CPreferences::tableUpload, sortAscending);
	// Sort table
	SetSortArrow(sortItem, sortAscending);
	SortItems(SortProc, sortItem + (sortAscending ? 0:10));

	*pResult = 0;
}

int CUploadListCtrl::SortProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort){
	CUpDownClient* item1 = (CUpDownClient*)lParam1;
	CUpDownClient* item2 = (CUpDownClient*)lParam2;
	CKnownFile* file1 = theApp.sharedfiles->GetFileByID(item1->reqfileid);
	CKnownFile* file2 = theApp.sharedfiles->GetFileByID(item2->reqfileid);
		switch(lParamSort){
		case 0: 
			return CString(item1->GetUserName()).CompareNoCase(item2->GetUserName());
		case 10:
			return CString(item2->GetUserName()).CompareNoCase(item1->GetUserName());
		case 1: 
			if( (file1 != NULL) && (file2 != NULL))
				return CString(file1->GetFileName()).CompareNoCase(file2->GetFileName());
			else if( file1 == NULL )
				return 1;
			else
				return -1;
		case 11:
			if( (file1 != NULL) && (file2 != NULL))
				return CString(file2->GetFileName()).CompareNoCase(file1->GetFileName());
			else if( file1 == NULL )
				return 1;
			else
				return -1;
		case 2: 
				return (float)item1->GetDatarate() - (float)item2->GetDatarate();
		case 12:
				return (float)item2->GetDatarate() - (float)item1->GetDatarate();

		case 3: 
			return item1->GetTransferedUp() - item2->GetTransferedUp();
		case 13: 
			return item2->GetTransferedUp() - item1->GetTransferedUp();

		case 4: 
			return item1->GetWaitTime() - item2->GetWaitTime();
		case 14: 
			return item2->GetWaitTime() - item1->GetWaitTime();
		case 5: 
			return item1->GetUpStartTimeDelay() - item2->GetUpStartTimeDelay();
		case 15: 
			return item2->GetUpStartTimeDelay() - item1->GetUpStartTimeDelay();
		case 6: 
			return item1->GetUploadState() - item2->GetUploadState();
		case 16: 
			return item2->GetUploadState() - item1->GetUploadState();
		case 7: // Add sort compression
			return item1->GetCompression() - item2->GetCompression();
		case 17: // Add sort compression
			return item2->GetCompression() - item1->GetCompression();
		default:
			return 0;
	}
}