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


// TransferWnd.cpp : implementation file
//

#include "stdafx.h"
#include "emule.h"
#include "TransferWnd.h"



// CTransferWnd dialog

IMPLEMENT_DYNAMIC(CTransferWnd, CDialog)
CTransferWnd::CTransferWnd(CWnd* pParent /*=NULL*/)
	: CResizableDialog(CTransferWnd::IDD, pParent)
{
}

CTransferWnd::~CTransferWnd()
{
}

BEGIN_MESSAGE_MAP(CTransferWnd, CResizableDialog)
	ON_NOTIFY_EX_RANGE(TTN_NEEDTEXT,0,0xFFFF,OnToolTipNotify)
	ON_BN_CLICKED(IDC_UPLOAD_ICO, OnBnClickedUploadIco)
	ON_BN_CLICKED(IDC_QUEUE_REFRESH_BUTTON, OnBnClickedQueueRefreshButton)
END_MESSAGE_MAP()


BOOL CTransferWnd::OnInitDialog(){
	CResizableDialog::OnInitDialog();
	windowtransferstate = 1;

	uploadlistctrl.Init();
	downloadlistctrl.Init();
	queuelistctrl.Init();

    Localize(); // i_a 

	((CStatic*)GetDlgItem(IDC_DOWNLOAD_ICO))->SetIcon((HICON)::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_DIRECTDOWNLOAD), IMAGE_ICON, 16, 16, 0));
	m_uplBtn.SetIcon(IDI_UPLOAD);	m_uplBtn.SetAlign(CButtonST::ST_ALIGN_HORIZ);
	m_uplBtn.SetFlat();
	m_uplBtn.SetLeftAlign(true); 
	
	AddAnchor(IDC_DOWNLOADLIST,TOP_LEFT,CSize(100, theApp.glob_prefs->GetSplitterbarPosition() ));
	AddAnchor(IDC_UPLOADLIST,CSize(0,theApp.glob_prefs->GetSplitterbarPosition()),BOTTOM_RIGHT);
	AddAnchor(IDC_QUEUELIST,CSize(0,theApp.glob_prefs->GetSplitterbarPosition()),BOTTOM_RIGHT);
	AddAnchor(IDC_UPLOAD_ICO,CSize(0,theApp.glob_prefs->GetSplitterbarPosition()),BOTTOM_RIGHT);
	AddAnchor(IDC_QUEUECOUNT,BOTTOM_LEFT);
	AddAnchor(IDC_TSTATIC1,BOTTOM_LEFT);
	AddAnchor(IDC_QUEUE_REFRESH_BUTTON, BOTTOM_RIGHT);

	// splitting functionality
	CRect rc,rcSpl,rcDown;

	GetWindowRect(rc);
	ScreenToClient(rc);

	rcSpl=rc; rcSpl.top=rc.bottom-100 ; rcSpl.bottom=rcSpl.top+5;rcSpl.left=55;
	m_wndSplitter.Create(WS_CHILD | WS_VISIBLE, rcSpl, this, IDC_SPLITTER);
	SetInitLayout();

	// create tooltip
	m_ttip.Create(this);
	m_ttip.SetDelayTime(TTDT_AUTOPOP, 20000);
	m_ttip.SetDelayTime(TTDT_INITIAL, theApp.glob_prefs->GetToolTipDelay()*1000);
	m_ttip.SendMessage(TTM_SETMAXTIPWIDTH, 0, SHRT_MAX); // recognize \n chars!
	m_ttip.AddTool(&downloadlistctrl);
	m_ttip.AddTool(&uploadlistctrl);
	m_iOldToolTipItemDown = -1;
	m_iOldToolTipItemUp = -1;
	m_iOldToolTipItemQueue = -1;

	return true;
}

void CTransferWnd::ShowQueueCount(uint32 number){
	char buffer[100];
	if (theApp.glob_prefs->GetQueueSize() == 0x7fff) {
		sprintf(buffer,"%u (%u "+ GetResString(IDS_BANNED).MakeLower() +")",number,theApp.uploadqueue->GetBanCount());
	} else {
		sprintf(buffer,"%u (%u "+ GetResString(IDS_BANNED).MakeLower() +") of possible %i clients",number,theApp.uploadqueue->GetBanCount(), theApp.glob_prefs->GetQueueSize());
	}
	this->GetDlgItem(IDC_QUEUECOUNT)->SetWindowText(buffer);
}

void CTransferWnd::DoDataExchange(CDataExchange* pDX)
{
	CResizableDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_UPLOADLIST, uploadlistctrl);
	DDX_Control(pDX, IDC_DOWNLOADLIST, downloadlistctrl);
	DDX_Control(pDX, IDC_QUEUELIST, queuelistctrl);
	DDX_Control(pDX, IDC_UPLOAD_ICO, m_uplBtn);
}

void CTransferWnd::SetInitLayout() {
		CRect rcDown,rcSpl,rcW;
		CWnd* pWnd;

		GetWindowRect(rcW);
		ScreenToClient(rcW);

		LONG splitpos=(theApp.glob_prefs->GetSplitterbarPosition()*rcW.Height())/100;

		pWnd = GetDlgItem(IDC_DOWNLOADLIST);
		pWnd->GetWindowRect(rcDown);
		ScreenToClient(rcDown);
		rcDown.right=rcW.right-7;
		rcDown.bottom=splitpos-5;
		downloadlistctrl.MoveWindow(rcDown);
		
		pWnd = GetDlgItem(IDC_UPLOADLIST);
		pWnd->GetWindowRect(rcDown);
		ScreenToClient(rcDown);
		rcDown.right=rcW.right-7;
		rcDown.bottom=rcW.bottom-20;
		rcDown.top=splitpos+20;
		uploadlistctrl.MoveWindow(rcDown);

		pWnd = GetDlgItem(IDC_QUEUELIST);
		pWnd->GetWindowRect(rcDown);
		ScreenToClient(rcDown);
		rcDown.right=rcW.right-7;
		rcDown.bottom=rcW.bottom-20;
		rcDown.top=splitpos+20;
		queuelistctrl.MoveWindow(rcDown);

		rcSpl=rcDown;
		rcSpl.top=rcDown.bottom+4;rcSpl.bottom=rcSpl.top+5;rcSpl.left=150;
		m_wndSplitter.MoveWindow(rcSpl,true);

		DoResize(0);
}

void CTransferWnd::DoResize(int delta)
{
	CSplitterControl::ChangeHeight(&downloadlistctrl, delta);
	CSplitterControl::ChangeHeight(&uploadlistctrl, -delta, CW_BOTTOMALIGN);
	CSplitterControl::ChangeHeight(&queuelistctrl, -delta, CW_BOTTOMALIGN);

	UpdateSplitterRange();

	Invalidate();
	UpdateWindow();
}

// setting splitter range limits
void CTransferWnd::UpdateSplitterRange()
{
		CRect rcDown,rcUp,rcW,rcSpl;
		CWnd* pWnd;

		GetWindowRect(rcW);
		ScreenToClient(rcW);

		pWnd = GetDlgItem(IDC_DOWNLOADLIST);
		pWnd->GetWindowRect(rcDown);
		ScreenToClient(rcDown);

		pWnd = GetDlgItem(IDC_UPLOADLIST);
		pWnd->GetWindowRect(rcUp);
		ScreenToClient(rcUp);

		pWnd = GetDlgItem(IDC_QUEUELIST);
		pWnd->GetWindowRect(rcUp);
		ScreenToClient(rcUp);

		theApp.glob_prefs->SetSplitterbarPosition((rcDown.bottom*100)/rcW.Height());

		RemoveAnchor(IDC_DOWNLOADLIST);RemoveAnchor(IDC_UPLOADLIST);RemoveAnchor(IDC_QUEUELIST);
		AddAnchor(IDC_DOWNLOADLIST,TOP_LEFT,CSize(100,theApp.glob_prefs->GetSplitterbarPosition() ));
		AddAnchor(IDC_UPLOADLIST,CSize(0,theApp.glob_prefs->GetSplitterbarPosition()),BOTTOM_RIGHT);
		AddAnchor(IDC_QUEUELIST,CSize(0,theApp.glob_prefs->GetSplitterbarPosition()),BOTTOM_RIGHT);

		m_wndSplitter.SetRange(rcDown.top+50 , rcUp.bottom-40);

}


LRESULT CTransferWnd::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	switch (message) {
		// arrange transferwindow layout
		case WM_PAINT:
			if (m_wndSplitter) {
				CRect rcDown,rcSpl,rcW;
				CWnd* pWnd;


				GetWindowRect(rcW);
				ScreenToClient(rcW);

				pWnd = GetDlgItem(IDC_DOWNLOADLIST);
				pWnd->GetWindowRect(rcDown);
				ScreenToClient(rcDown);

				if (rcW.Height()>0) {
					// splitter paint update
					rcSpl=rcDown;
					rcSpl.top=rcDown.bottom+8;rcSpl.bottom=rcSpl.top+5;rcSpl.left=150;
					GetDlgItem(IDC_UPLOAD_ICO)->MoveWindow(10,rcSpl.top-4,130,18);
					m_wndSplitter.MoveWindow(rcSpl,true);
					UpdateSplitterRange();
				}
			}
			break;
		case WM_NOTIFY:
			if (wParam == IDC_SPLITTER)
			{	
				SPC_NMHDR* pHdr = (SPC_NMHDR*) lParam;
				DoResize(pHdr->delta);
			}
			break;
		case WM_WINDOWPOSCHANGED : 
			{
				CRect rcW;
				GetWindowRect(rcW);
				ScreenToClient(rcW);

				if (m_wndSplitter && rcW.Height()>0) Invalidate();
				break;
			}
		case WM_SIZE:
			if (m_wndSplitter) {
				CRect rcDown,rcSpl,rcW;
				CWnd* pWnd;

				GetWindowRect(rcW);
				ScreenToClient(rcW);

				if (rcW.Height()>0){
					pWnd = GetDlgItem(IDC_DOWNLOADLIST);
					pWnd->GetWindowRect(rcDown);
					ScreenToClient(rcDown);

					long splitpos=(theApp.glob_prefs->GetSplitterbarPosition()*rcW.Height())/100;

					rcSpl.right=rcDown.right;rcSpl.top=splitpos+10;rcSpl.bottom=rcSpl.top+5;rcSpl.left=150;
					m_wndSplitter.MoveWindow(rcSpl,true);
				}

			}
			break;
	}
	return CResizableDialog::DefWindowProc(message, wParam, lParam);
}



// CTransferWnd message handlers
BOOL CTransferWnd::PreTranslateMessage(MSG* pMsg)
{
	// handle tooltip updating, when mouse is moved from one item to another
	if (pMsg->message== WM_MOUSEMOVE)
		UpdateToolTips();

	// relay mouse events to tooltip control
	if (pMsg->message== WM_LBUTTONDOWN || pMsg->message== WM_LBUTTONUP || pMsg->message== WM_MOUSEMOVE)
		m_ttip.RelayEvent(pMsg);

	return CResizableDialog::PreTranslateMessage(pMsg);
}

void CTransferWnd::UpdateToolTips(void)
{
	int sel = GetItemUnderMouse(&downloadlistctrl);
	if (sel != -1)
	{
		if (sel != m_iOldToolTipItemDown)
		{
			if (m_ttip.IsWindowVisible())
				m_ttip.Update();
			m_iOldToolTipItemDown = sel;
			return;
		}
	}
	int sel2 = GetItemUnderMouse(&uploadlistctrl);
	if (sel2 != -1)
	{
		if (sel2 != m_iOldToolTipItemUp)
		{
			if (m_ttip.IsWindowVisible())
				m_ttip.Update();
			m_iOldToolTipItemUp = sel2;
			return;
		}
	}
/* no tooltips needed ATM
	int sel3 = GetItemUnderMouse(&queuelistctrl);
	if (sel3 != -1)
	{
		if (sel3 != m_iOldToolTipItemQueue)
		{
			if (m_ttip.IsWindowVisible())
				m_ttip.Update();
			m_iOldToolTipItemQueue = sel3;
		}
	}
*/
	if (sel == -1 && sel2 == -1 /*&& sel3 != -1*/)
		m_ttip.Pop();

}

int CTransferWnd::GetItemUnderMouse(CListCtrl* ctrl)
{
	CPoint pt;
	::GetCursorPos(&pt);
	ctrl->ScreenToClient(&pt);
	LVHITTESTINFO hit, subhit;
	hit.pt = pt;
	subhit.pt = pt;
	ctrl->SubItemHitTest(&subhit);
	int sel = ctrl->HitTest(&hit);
	if (sel != LB_ERR && (hit.flags & LVHT_ONITEM))
	{
		if (subhit.iSubItem == 0)
			return sel;
	}
	return LB_ERR;
}

BOOL CTransferWnd::OnToolTipNotify(UINT id, NMHDR *pNMH, LRESULT *pResult)
{
	TOOLTIPTEXT *pText = (TOOLTIPTEXT *)pNMH;
	int control_id = ::GetDlgCtrlID((HWND)pNMH->idFrom);
	if (!control_id)
		return FALSE;
	CString info;
	if (control_id == IDC_DOWNLOADLIST)
	{
		if (downloadlistctrl.GetItemCount() < 1)
			return FALSE;
		int sel = GetItemUnderMouse(&downloadlistctrl);
		if (sel < 0 || sel == 65535)
			return FALSE;

		// build info text and display it
		CtrlItem_Struct* content = (CtrlItem_Struct*)downloadlistctrl.GetItemData(sel);
		if (content->type == 1) // for downloading files
		{
			CPartFile* partfile = (CPartFile*)content->value;
			CString strHash;
			strHash.Format("%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
			partfile->GetFileHash()[0],partfile->GetFileHash()[1],partfile->GetFileHash()[2],partfile->GetFileHash()[3],partfile->GetFileHash()[4],partfile->GetFileHash()[5],partfile->GetFileHash()[6],partfile->GetFileHash()[7],
			partfile->GetFileHash()[8],partfile->GetFileHash()[9],partfile->GetFileHash()[10],partfile->GetFileHash()[11],partfile->GetFileHash()[12],partfile->GetFileHash()[13],partfile->GetFileHash()[14],partfile->GetFileHash()[15]);

			CTime t(partfile->GetFileDate());
			char lsc[50]; char compl[50]; char buffer[20];

			CastItoXBytes(partfile->GetCompletedSize(),lsc);
			CastItoXBytes(partfile->GetFileSize() ,buffer);
			sprintf(compl,"%s/%s",lsc,buffer);

			if (partfile->lastseencomplete==NULL) sprintf(lsc,GetResString(IDS_UNKNOWN).MakeLower() ); else
			sprintf(lsc,partfile->lastseencomplete.Format( "%A, %x, %X"));

			float availability = 0;
			if(partfile->GetPartCount() != 0) {
				availability = partfile->GetAvailablePartCount() * 100 / partfile->GetPartCount();
			}
			info.Format(GetResString(IDS_DL_FILENAME)+": %s (%d %s)\n"
				+GetResString(IDS_DATE)+": %s - "+ GetResString(IDS_FD_HASH) +" %s\n"
				+GetResString(IDS_PARTINFOS)+
				GetResString(IDS_PARTINFOS2)+"\n%s",
						partfile->GetFileName(), partfile->GetFileSize(),GetResString(IDS_BYTES),
						t.Format("%A, %B %d, %Y"), strHash,
						partfile->GetPartMetFileName(), partfile->GetPartCount(),GetResString(IDS_AVAIL),partfile->GetAvailablePartCount(),availability,
						(int)partfile->GetPercentCompleted(), compl, partfile->GetTransferingSrcCount(),
						GetResString(IDS_LASTSEENCOMPL)+" "+CString(lsc));
		}
		else if (content->type == 3 || content->type == 2) // for sources
		{
			CUpDownClient* client = (CUpDownClient*)content->value;
			in_addr server;
			server.S_un.S_addr = client->GetServerIP();

			info.Format(GetResString(IDS_NICKNAME)+" %s ("+GetResString(IDS_USERID)+": %u)\n"
				+GetResString(IDS_CLIENT)+" %s:%d\n"
				+GetResString(IDS_SERVER)+" %s:%d\n"
				+GetResString(IDS_SOURCEINFO),
						client->GetUserName(), client->GetUserID(),
						client->GetFullIP(), client->GetUserPort(), 
						inet_ntoa(server), client->GetServerPort(),
						client->GetAskedCountDown(), client->GetAvailablePartCount());
			if (content->type == 2)
			{	// normal client
				info += GetResString(IDS_CLIENTSOURCENAME) + CString(client->GetClientFilename());
			}
			else
			{	// client asked twice
				info += GetResString(IDS_ASKEDFAF);
			}
         //-For File Comment-// 
         try { 
			 if (content->type==2){
				if (client->GetFileComment() != "") { 
					info += "\n" + GetResString(IDS_CMT_READ)  + " " + CString(client->GetFileComment()); 
				} 
				else { 
					//No comment entered 
					info += "\n" + GetResString(IDS_CMT_NONE); 
				} 
				info += "\n" + GetRateString(client->GetFileRate());
			 }
         } catch(...) { 
            //Information not received = not connected or connecting 
            info += "\n" + GetResString(IDS_CMT_NOTCONNECTED); 
         } 
         //-End file comment-//
		}
	}
	else if (control_id == IDC_UPLOADLIST)
	{
		if (uploadlistctrl.GetItemCount() < 1)
			return FALSE;
		int sel = GetItemUnderMouse(&uploadlistctrl);
		if (sel < 0 || sel == 65535)
			return FALSE;

		CUpDownClient* client = (CUpDownClient*)uploadlistctrl.GetItemData(sel);
		CKnownFile* file = theApp.sharedfiles->GetFileByID(client->reqfileid);
		// build info text and display it
		info.Format(GetResString(IDS_USERINFO), client->GetUserName(), client->GetUserID());
		if (file)
		{
			info += GetResString(IDS_SF_REQUESTED) + CString(file->GetFileName()) + "\n";
			CString stat;
			stat.Format(GetResString(IDS_FILESTATS_SESSION)+GetResString(IDS_FILESTATS_TOTAL),
						file->statistic.GetAccepts(), file->statistic.GetRequests(), file->statistic.GetTransfered(),
						file->statistic.GetAllTimeAccepts(), file->statistic.GetAllTimeRequests(), file->statistic.GetAllTimeTransfered());
			info += stat;
		}
		else
		{
			info += GetResString(IDS_REQ_UNKNOWNFILE);
		}

	}
/*	no tooltips needed ATM
	else if (control_id == IDC_QUEUELIST)
	{
		if (queuelistctrl.GetItemCount() < 1)
			return FALSE;
		int sel = GetItemUnderMouse(&queuelistctrl);
		if (sel < 0 || sel == 65535)
			return FALSE;

		// build info text and display it
		CUpDownClient* client = (CUpDownClient*)uploadlistctrl.GetItemData(sel);
		in_addr server;
		server.S_un.S_addr = client->GetServerIP();

		info.Format("Nickname: %s (UserID: %u)\n"
					"Client %s:%d\n"
					"Server %s:%d\n"
					"AskedCount: %d - AvailablePartCount: %d",
					client->GetUserName(), client->GetUserID(),
					client->GetFullIP(), client->GetUserPort(), 
					inet_ntoa(server), client->GetServerPort(),
					client->GetAskedCount(), client->GetAvailablePartCount());

	}
*/
	m_strToolTip.ReleaseBuffer(); // release old used buffer
	m_strToolTip = info;
	pText->lpszText = m_strToolTip.GetBuffer(1);
	pText->hinst = NULL; // we are not using a resource
	PostMessage(WM_ACTIVATE);
	return TRUE;
}

void CTransferWnd::SwitchUploadList()
{
	if( windowtransferstate == 1){
		uploadlistctrl.Hide();
		GetDlgItem(IDC_QUEUE_REFRESH_BUTTON)->ShowWindow(SW_SHOW);
		queuelistctrl.Visable();
		windowtransferstate = 0;
		
		GetDlgItem(IDC_UPLOAD_ICO)->SetWindowText(GetResString(IDS_ONQUEUE));
	}
	else{
		queuelistctrl.Hide();
		uploadlistctrl.Visable();
		GetDlgItem(IDC_QUEUE_REFRESH_BUTTON)->ShowWindow(SW_HIDE);
		windowtransferstate = 1;
		GetDlgItem(IDC_UPLOAD_ICO)->SetWindowText(GetResString(IDS_TW_UPLOADS));
	}
}

void CTransferWnd::Localize(){
	GetDlgItem(IDC_DOWNLOAD_TEXT)->SetWindowText(GetResString(IDS_TW_DOWNLOADS));
	GetDlgItem(IDC_UPLOAD_ICO)->SetWindowText(GetResString(IDS_TW_UPLOADS));
	GetDlgItem(IDC_TSTATIC1)->SetWindowText(GetResString(IDS_TW_QUEUE));
	GetDlgItem(IDC_QUEUE_REFRESH_BUTTON)->SetWindowText(GetResString(IDS_SV_UPDATE));

	uploadlistctrl.Localize();
	queuelistctrl.Localize();
	downloadlistctrl.Localize();
}

void CTransferWnd::OnBnClickedUploadIco()
{
	SwitchUploadList();
}

void CTransferWnd::OnBnClickedQueueRefreshButton()
{
	CUpDownClient* update = theApp.uploadqueue->GetNextClient(NULL);

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