//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.

// QueueListCtrl.cpp : implementation file
//

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

// CQueueListCtrl

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

	// Barry - Refresh the queue every 10 secs
	m_hTimer = ::SetTimer(NULL,				// Window to associate with
						NULL,				// ID of timer (ignored if window = null)
						30000,				// Time out duration
						(TIMERPROC)CQueueListCtrl::QueueUpdateTimer);	// Proc to run
	if (!m_hTimer)
		theApp.emuledlg->AddLogLine(false, GetResString(IDS_ERR_TIMERCREATEFAILED));
}

void CQueueListCtrl::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_FILEPRIO),LVCFMT_LEFT,110,2);
	InsertColumn(3,GetResString(IDS_QL_RATING),LVCFMT_LEFT,60,3);
	InsertColumn(4,GetResString(IDS_SCORE),LVCFMT_LEFT,60,4);

	InsertColumn(5,IDS_SFRATIO,LVCFMT_LEFT,60,5); // Added by Tarod
	InsertColumn(6,IDS_RFRATIO,LVCFMT_LEFT,60,6); // Added by Tarod

	InsertColumn(7,GetResString(IDS_ASKED),LVCFMT_LEFT,60,7);
	InsertColumn(8,GetResString(IDS_LASTSEEN),LVCFMT_LEFT,110,8);
	InsertColumn(9,GetResString(IDS_ENTERQUEUE),LVCFMT_LEFT,110,9);
	InsertColumn(10,GetResString(IDS_BANNED),LVCFMT_LEFT,60,10);
	imagelist.Create(16,16,ILC_COLOR32 | ILC_MASK,0,14);
	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_TAROD)); // Added by Tarod
	imagelist.Add(theApp.LoadIcon(IDI_TARODPLUS)); // Added by Tarod

	imagelist.Add(theApp.LoadIcon(IDI_FRIEND));
	SetImageList(&imagelist,LVSIL_SMALL);

	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_UNBAN, GetResString(IDS_UNBAN));
	m_ClientMenu.AppendMenu(MF_STRING,MP_SHOWLIST, GetResString(IDS_VIEWFILES));
	m_ClientMenu.AppendMenu(MF_SEPARATOR);
	m_ClientMenu.AppendMenu(MF_STRING,MP_SWITCHCTRL, GetResString(IDS_VIEWUPLOADS));
	SetMenu(&m_ClientMenu);
	LoadSettings(CPreferences::tableQueue);

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

CQueueListCtrl::~CQueueListCtrl()
{
	// Barry - Kill the timer that was created
	try
	{
		if (m_hTimer)
			::KillTimer(NULL, m_hTimer);
	} catch (...) {}
}

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

	if(pHeaderCtrl->GetItemCount() != 0) {
		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_FILEPRIO);
		hdi.pszText = strRes.GetBuffer();
		pHeaderCtrl->SetItem(2, &hdi);
		strRes.ReleaseBuffer();

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

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

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

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

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

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

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

		strRes = GetResString(IDS_BANNED);
		hdi.pszText = strRes.GetBuffer();
		pHeaderCtrl->SetItem(10, &hdi);
		strRes.ReleaseBuffer();
	}
}

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

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

void CQueueListCtrl::RefreshClient(CUpDownClient* client, bool updatetime, bool newclient){
	LVFINDINFO find;
	find.flags = LVFI_PARAM;
	find.lParam = (LPARAM)client;
	sint32 itemnr = FindItem(&find);
	if (itemnr == (-1))
		return;
	char buffer[100];
	char dtmpbuf[128];
	char ttmpbuf[128];
	sprintf(buffer,"%i",client->GetAskedCount());
	SetItemText(itemnr,7,buffer);
	if( updatetime && !client->IsBanned()){
	    _strtime( ttmpbuf );
		_strdate( dtmpbuf );
		sprintf( buffer, "%s %s", dtmpbuf, ttmpbuf );
		SetItemText(itemnr,8,buffer);
	}
	else if( updatetime ){
		sprintf( buffer, "--" );
		SetItemText(itemnr,8,buffer);
	}
	else if( client->IsBanned()){
		return; //Now if you get a very bad client, it will only update the count.. Not everything else to save cpu.
	}

	uint8 image;
	if (client->IsFriend()) {
		image = 6;
	} else if (client->ExtProtocolAvailable()) {
		if (client->credits->GetScoreRatio() > 1) {
			if (client->IsTarodVersion()) image = 5; else image = 3;
		} else {
			if (client->IsTarodVersion()) image = 4; else image = 1;
	}
	} else {
		if (client->credits->GetScoreRatio() > 1) image = 2; else image = 0;
	}
	SetItem(itemnr,0,LVIF_IMAGE,0,image,0,0,0,0);

	CKnownFile* file = theApp.sharedfiles->GetFileByID(client->reqfileid);
	if (file)
		SetItemText(itemnr,1,file->GetFileName());
	else
		SetItemText(itemnr,1,"?");
	if(file){
		switch(file->GetPriority()){ 
					case PR_VERYHIGH:
						sprintf(buffer,GetResString(IDS_PRIORELEASE));
						break;
					case PR_HIGH: 
						sprintf(buffer,GetResString(IDS_PRIOHIGH));
						break; 
					case PR_LOW: 
						sprintf(buffer,GetResString(IDS_PRIOLOW));
						break; 
					case PR_VERYLOW:
						sprintf(buffer,GetResString(IDS_PRIOVERYLOW));
						break;
					default: 
						sprintf(buffer,GetResString(IDS_PRIONORMAL));
					break; 
		}
	}
	else
		sprintf(buffer,"?");
	SetItemText(itemnr,2,buffer);
	sprintf(buffer,"%u",client->GetScore(false,client->IsDownloading(),true));
	SetItemText(itemnr,3,buffer);
	sprintf(buffer,"%i",client->GetScore(false));
	SetItemText(itemnr,4,buffer);

	// Added by Tarod for push ratios
	sprintf(buffer, "%.1f", client->GetSmallFilePushRatio()) ;
	SetItemText(itemnr,5,buffer);
	sprintf(buffer, "%.1f", client->GetRareFilePushRatio()) ;
	SetItemText(itemnr, 6, buffer) ;
	// End added by Tarod

	if( newclient ){
		_strtime( ttmpbuf );
		_strdate( dtmpbuf );
		sprintf( buffer, "%s %s", dtmpbuf, ttmpbuf );
		SetItemText(itemnr,9,buffer);
	}
	if(client->IsBanned())
		sprintf(buffer,GetResString(IDS_YES));

	else
		sprintf(buffer,GetResString(IDS_NO));
	SetItemText(itemnr,10,buffer);
	client->SetUpStartTime();
}

BEGIN_MESSAGE_MAP(CQueueListCtrl, CMuleListCtrl)
	ON_NOTIFY_REFLECT (NM_RCLICK, OnNMRclick)
	ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnColumnClick)
END_MESSAGE_MAP()



// CQueueListCtrl message handlers
void CQueueListCtrl::OnNMRclick(NMHDR *pNMHDR, LRESULT *pResult){	
	POINT point;
	::GetCursorPos(&point);	
	m_ClientMenu.TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, point.x, point.y, this);
	*pResult = 0;
}

BOOL CQueueListCtrl::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_UNBAN:{
				if( client->IsBanned() )
					client->UnBan();
				break;
			}
			case MP_DETAIL:
				CClientDetailDialog dialog(client);
				dialog.DoModal();
				break;

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

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

//	theApp.uploadqueue->ResetClientPos();
	CUpDownClient* update = theApp.uploadqueue->GetNextClient(NULL);

	while( update ){
		RefreshClient( update, false);
		update = theApp.uploadqueue->GetNextClient(update);
	}

	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::tableQueue);
	bool m_oldSortAscending = theApp.glob_prefs->GetColumnSortAscending(CPreferences::tableQueue);
	bool sortAscending = (sortItem != pNMListView->iSubItem) ? true : !m_oldSortAscending;
	// Item is column clicked
	sortItem = pNMListView->iSubItem;
	// Save new preferences
	theApp.glob_prefs->SetColumnSortItem(CPreferences::tableQueue, sortItem);
	theApp.glob_prefs->SetColumnSortAscending(CPreferences::tableQueue, sortAscending);
	// Sort table
	SetSortArrow(sortItem, sortAscending);
	SortItems(SortProc, sortItem + (sortAscending ? 0:100));

	*pResult = 0;
}

int CQueueListCtrl::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 100:
			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 101:
			if( (file1 != NULL) && (file2 != NULL))
				return CString(file2->GetFileName()).CompareNoCase(file1->GetFileName());
			else if( file1 == NULL )
				return 1;
			else
				return -1;
		case 2: 
			if( (file1 != NULL) && (file2 != NULL))
				return file1->GetPriority() - file2->GetPriority();
			else if( file1 == NULL )
				return 1;
			else
				return -1;
		case 102:
			if( (file1 != NULL) && (file2 != NULL))
				return file2->GetPriority() - file1->GetPriority();
			else if( file1 == NULL )
				return 1;
			else
				return -1;

		case 3: 
		return item1->GetScore(false,false,true) - item2->GetScore(false,false,true);
		case 103: 
			return item2->GetScore(false,false,true) - item1->GetScore(false,false,true);

		case 4: 
			return item1->GetScore(false) - item2->GetScore(false);
		case 104: 
			return item2->GetScore(false) - item1->GetScore(false);

		// Added by Tarod
		case 5: //speed asc
			return (int)(item1->GetSmallFilePushRatio()*100 - item2->GetSmallFilePushRatio()*100);
		case 105: //speed desc
			return (int)(item2->GetSmallFilePushRatio()*100 - item1->GetSmallFilePushRatio()*100);
		case 6: //speed asc
			return (int)(item1->GetRareFilePushRatio()*100 - item2->GetRareFilePushRatio()*100);
		case 106: //speed desc
			return (int)(item2->GetRareFilePushRatio()*100 - item1->GetRareFilePushRatio()*100);
		// End by Tarod

		case 7: 
		return item1->GetAskedCount() - item2->GetAskedCount();
		case 107: 
			return item2->GetAskedCount() - item1->GetAskedCount();
		case 8: 
			return item1->GetLastUpRequest() - item2->GetLastUpRequest();
		case 108: 
			return item2->GetLastUpRequest() - item1->GetLastUpRequest();
		case 9: 
			return item1->GetWaitStartTime() - item2->GetWaitStartTime();
		case 109: 
			return item2->GetWaitStartTime() - item1->GetWaitStartTime();
		case 10: 
			return item1->IsBanned() - item2->IsBanned();
		case 110: 
			return item2->IsBanned() - item1->IsBanned();

		default:
			return 0;
	}
}

// Barry - Refresh the queue every 10 secs
void CALLBACK CQueueListCtrl::QueueUpdateTimer(HWND hwnd, UINT uiMsg, UINT idEvent, DWORD dwTime)
{
	// Don't do anything if the app is shutting down - can cause unhandled exceptions
	if (!theApp.emuledlg->IsRunning() || !theApp.glob_prefs->GetUpdateQueueList())
		return;

	CUpDownClient* update = theApp.uploadqueue->GetNextClient(NULL);
	while( update )
	{
		theApp.emuledlg->transferwnd.queuelistctrl.RefreshClient(update);
		update = theApp.uploadqueue->GetNextClient(update);
	}
}
