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

// FileDetailDialog.cpp : implementation file
//

#include "stdafx.h"
#include "emule.h"
#include "FileDetailDialog.h"
#include "otherfunctions.h"
#include "FileInfoDialog.h"
#include "commentdialoglst.h"

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


// CFileDetailDialog dialog

IMPLEMENT_DYNAMIC(CFileDetailDialog, CDialog)
CFileDetailDialog::CFileDetailDialog(CPartFile* file)
	: CDialog(CFileDetailDialog::IDD, 0)
{
	m_file = file;
}

CFileDetailDialog::~CFileDetailDialog()
{
}

void CFileDetailDialog::OnTimer(UINT nIDEvent) {
	UpdateData();
}

void CFileDetailDialog::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BOOL CFileDetailDialog::OnInitDialog(){
	CDialog::OnInitDialog();
	Localize();
	m_timer=SetTimer(301, 5000, 0);
	UpdateData();

	return true;
}

void CFileDetailDialog::UpdateData(){
	CString bufferS;

	GetDlgItem(IDC_FNAME)->SetWindowText(MakeStringEscaped(m_file->GetFileName()));
	GetDlgItem(IDC_METFILE)->SetWindowText(m_file->GetFullName());
    GetDlgItem(IDC_FILENAME)->GetWindowText(bufferS);
	if (bufferS.GetLength()<3)
		GetDlgItem(IDC_FILENAME)->SetWindowText(m_file->GetFileName());

	GetDlgItem(IDC_FHASH)->SetWindowText(EncodeBase16(m_file->GetFileHash(), 16));

	GetDlgItem(IDC_FSIZE)->SetWindowText(CastItoXBytes(m_file->GetFileSize()));

	GetDlgItem(IDC_PFSTATUS)->SetWindowText(m_file->getPartfileStatus());
	
	bufferS.Format("%i(%i)",m_file->GetPartCount(),m_file->GetHashCount());
	GetDlgItem(IDC_PARTCOUNT)->SetWindowText(bufferS);

	GetDlgItem(IDC_TRANSFERED)->SetWindowText(CastItoXBytes(m_file->GetTransfered()));

	bufferS.Format(GetResString(IDS_FD_STATS),CastItoXBytes(m_file->GetLostDueToCorruption()), CastItoXBytes(m_file->GetGainDueToCompression()), m_file->TotalPacketsSavedDueToICH() );
	GetDlgItem(IDC_FD_STATS)->SetWindowText(bufferS);

	GetDlgItem(IDC_COMPLSIZE)->SetWindowText(CastItoXBytes(m_file->GetCompletedSize()));

	bufferS.Format("%.2f ",m_file->GetPercentCompleted());
	GetDlgItem(IDC_PROCCOMPL)->SetWindowText(bufferS+GetResString(IDS_PROCDONE));

    if((float)m_file->GetDatarate()/1024 >= 0) {
        bufferS.Format("%.2f %s",(float)m_file->GetDatarate()/1024,GetResString(IDS_KBYTESEC));
    } else {
        bufferS.Format("?? %s",GetResString(IDS_KBYTESEC));
    }

    GetDlgItem(IDC_DATARATE)->SetWindowText(bufferS);

	bufferS.Format("%i",m_file->GetSourceCount());
	GetDlgItem(IDC_SOURCECOUNT)->SetWindowText(bufferS);
	bufferS.Format("%i",m_file->GetTransferingSrcCount());
	GetDlgItem(IDC_SOURCECOUNT2)->SetWindowText(bufferS);

	bufferS.Format("%i (%.1f%%)",m_file->GetAvailablePartCount(),(float) ((m_file->GetAvailablePartCount()*100)/ m_file->GetPartCount()));
	GetDlgItem(IDC_PARTAVAILABLE)->SetWindowText(bufferS);

	if (m_file->lastseencomplete==NULL) bufferS.Format(GetResString(IDS_UNKNOWN).MakeLower()); else
		bufferS.Format( "%s",m_file->lastseencomplete.Format( "%A, %x, %X"));

	GetDlgItem(IDC_LASTSEENCOMPL)->SetWindowText(bufferS);
	GetDlgItem(IDC_RENAME)->EnableWindow((m_file->GetStatus() == PS_COMPLETE || m_file->GetStatus() == PS_COMPLETING) ? false:true);//add by CML 
	GetDlgItem(IDC_FILEINFO)->EnableWindow(m_file->IsMovie()); // added by quekky
}

void CFileDetailDialog::OnDestroy() {
	 if (m_timer) KillTimer(m_timer);
}

BEGIN_MESSAGE_MAP(CFileDetailDialog, CDialog)
	ON_WM_TIMER()
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_BUTTONSTRIP, OnBnClickedButtonStrip)
	ON_BN_CLICKED(IDC_TAKEOVER, TakeOver)	
	ON_BN_CLICKED(IDC_FILEINFO, OnBnClickedFileinfo)
	ON_NOTIFY(LVN_COLUMNCLICK, IDC_LISTCTRLFILENAMES, OnLvnColumnclick)
	ON_NOTIFY(NM_DBLCLK, IDC_LISTCTRLFILENAMES, OnNMDblclkList)
	ON_NOTIFY(NM_RCLICK, IDC_LISTCTRLFILENAMES, OnNMRclickList)
	ON_BN_CLICKED(IDC_CMTBT, OnBnClickedShowComment) //for comment
	ON_BN_CLICKED(IDC_RENAME, Rename) // Added by Tarod [Juanjo]
END_MESSAGE_MAP()


// CFileDetailDialog message handlers

void CFileDetailDialog::Localize(){
	GetDlgItem(IDC_FD_X0)->SetWindowText(GetResString(IDS_FD_GENERAL));
	GetDlgItem(IDC_FD_X1)->SetWindowText(GetResString(IDS_FD_NAME));
	GetDlgItem(IDC_FD_X2)->SetWindowText(GetResString(IDS_FD_MET));
	GetDlgItem(IDC_FD_X3)->SetWindowText(GetResString(IDS_FD_HASH));
	GetDlgItem(IDC_FD_X4)->SetWindowText(GetResString(IDS_FD_SIZE));
	GetDlgItem(IDC_FD_X5)->SetWindowText(GetResString(IDS_FD_STATUS));
	GetDlgItem(IDC_FD_X6)->SetWindowText(GetResString(IDS_FD_TRANSFER));
	GetDlgItem(IDC_FD_X7)->SetWindowText(GetResString(IDS_FD_SOURCES));
	GetDlgItem(IDC_FD_X10)->SetWindowText(GetResString(IDS_FD_TRANSI));
	GetDlgItem(IDC_FD_X9)->SetWindowText(GetResString(IDS_FD_PARTS));
	GetDlgItem(IDC_FD_X14)->SetWindowText(GetResString(IDS_FD_TRANS));
	GetDlgItem(IDC_FD_X12)->SetWindowText(GetResString(IDS_FD_COMPSIZE));
	GetDlgItem(IDC_FD_X13)->SetWindowText(GetResString(IDS_FD_DATARATE));
	GetDlgItem(IDC_FD_X11)->SetWindowText(GetResString(IDS_AVAIL)+":");
	GetDlgItem(IDC_FD_X15)->SetWindowText(GetResString(IDS_LASTSEENCOMPL));
	GetDlgItem(IDC_TAKEOVER)->SetWindowText(GetResString(IDS_TAKEOVER));
	GetDlgItem(IDC_BUTTONSTRIP)->SetWindowText(GetResString(IDS_CLEANUP));
	GetDlgItem(IDC_RENAME)->SetWindowText(GetResString(IDS_RENAME));
	GetDlgItem(IDC_FD_SN)->SetWindowText(GetResString(IDS_SOURCENAMES));
	GetDlgItem(IDC_FILEINFO)->SetWindowText(GetResString(IDS_FILEINFO));
	GetDlgItem(IDC_CMTBT)->SetWindowText(GetResString(IDS_CMT_SHOWALL));//For Comment 		

	GetDlgItem(IDOK)->SetWindowText(GetResString(IDS_FD_CLOSE));
	SetWindowText(GetResString(IDS_FD_TITLE));
	FillSourcenameList();
}

void CFileDetailDialog::FillSourcenameList() {
   // by Juanjo
   POSITION pos1,pos2; 
   CUpDownClient* cur_src; 
   CListCtrl* pmyListCtrl; 
   LVFINDINFO info; 
   info.flags = LVFI_STRING; 
   int itempos; 
   int namecount; 
   
   CString nameCountStr; 
   pmyListCtrl = (CListCtrl*)GetDlgItem(IDC_LISTCTRLFILENAMES); 
   if (pmyListCtrl->GetHeaderCtrl()->GetItemCount() < 2) { 
      pmyListCtrl->DeleteColumn(0); 
	  pmyListCtrl->InsertColumn(0, GetResString(IDS_DL_FILENAME), LVCFMT_LEFT, 340, -1); 
	  pmyListCtrl->InsertColumn(1, GetResString(IDS_DL_SOURCES), LVCFMT_LEFT, 60, 1); 
   }
   
   CString strText; 
   pmyListCtrl->DeleteAllItems(); 
   for (int sl=0;sl<SOURCESSLOTS;sl++) if (!m_file->srclists[sl].IsEmpty())
   for (pos1 = m_file->srclists[sl].GetHeadPosition(); (pos2 = pos1) != NULL;) { 
      m_file->srclists[sl].GetNext(pos1); 
      cur_src = m_file->srclists[sl].GetAt(pos2); 
      info.psz = cur_src->GetClientFilename(); 
      if (info.psz != 0) { 
         if ((itempos=pmyListCtrl->FindItem(&info, -1)) == -1) { 
            pmyListCtrl->InsertItem(0, cur_src->GetClientFilename()); 
            pmyListCtrl->SetItemText(0, 1, "1"); 
            pmyListCtrl->SetItemData(0, 1); 
         } else { 
            namecount = atoi(pmyListCtrl->GetItemText(itempos, 1)); 
            namecount ++; 
            nameCountStr.Format("%i", namecount); 
            pmyListCtrl->SetItemText(itempos, 1, nameCountStr.GetString()); 
            pmyListCtrl->SetItemData(itempos, namecount); 
         } 
        pmyListCtrl->SortItems(CompareListNameItems, 11); 
		m_SortAscending[0] =true;m_SortAscending[1] =false;
      } 
   } 
   // End by Juanjo
}

void CFileDetailDialog::TakeOver() {
   CListCtrl* pmyListCtrl; 
   int itemPosition; 

   pmyListCtrl = (CListCtrl*)GetDlgItem(IDC_LISTCTRLFILENAMES);
   if (pmyListCtrl->GetSelectedCount() > 0) {
      POSITION pos = pmyListCtrl->GetFirstSelectedItemPosition(); 
      itemPosition = pmyListCtrl->GetNextSelectedItem(pos); 
	  GetDlgItem(IDC_FILENAME)->SetWindowText(pmyListCtrl->GetItemText(itemPosition,0));
   } 
}

void CFileDetailDialog::OnBnClickedButtonStrip() {
	CString filename,tempStr;
	char c;

	GetDlgItem(IDC_FILENAME)->GetWindowText(filename);
	
	// Replace . with Spaces - except the last one (extention-dot)
	int extpos=filename.ReverseFind('.');
	if (extpos>=0) {
		filename.Replace('.',' ');
		filename.SetAt(extpos,'.');
	}

	// Replace Space-holders with Spaces
	filename.Replace('_',' ');
	filename.Replace("%20"," ");

	// Barry - Some additional formatting
	filename.MakeLower();
	filename.Replace("sharereactor", "");
	filename.Replace("deviance", "");
	filename.Replace("-ftv", "");
	filename.Replace("flt", "");
	filename.Replace("[]", "");
	filename.Replace("()", "");
	filename.Replace("  ", " ");

	// Make leading Caps 
	if (filename.GetLength()>1)
	{
		tempStr=filename.GetAt(0);
		tempStr.MakeUpper();
		c = tempStr.GetAt(0);
		filename.SetAt(0, c);
		
		for (int ix=0; ix<filename.GetLength()-1; ix++)
		{
			if (filename.GetAt(ix) == ' ') 
			{
				tempStr=filename.GetAt(ix+1);
				tempStr.MakeUpper();
				c=tempStr.GetAt(0);
				filename.SetAt(ix+1,c);
			}
		}
	}

	GetDlgItem(IDC_FILENAME)->SetWindowText(MakeStringEscaped(filename));
}

// added by quekky
void CFileDetailDialog::OnBnClickedFileinfo()
{
	CFileInfoDialog dialog(m_file);
	dialog.DoModal();
}

void CFileDetailDialog::OnLvnColumnclick(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
	
	m_SortAscending[pNMLV->iSubItem] = !m_SortAscending[pNMLV->iSubItem];
	//SetSortArrow(pNMLV->iSubItem, m_SortAscending[pNMLV->iSubItem]);

	CListCtrl* pmyListCtrl; 
	pmyListCtrl = (CListCtrl*)GetDlgItem(IDC_LISTCTRLFILENAMES);

	pmyListCtrl->SortItems(&CompareListNameItems,pNMLV->iSubItem+((m_SortAscending[pNMLV->iSubItem])? 0:10));

	*pResult = 0;
}

int CALLBACK CFileDetailDialog::CompareListNameItems(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort){ 
	switch (lParamSort){
		case 1: return (lParam1 - lParam2); break;
		case 11: return (lParam2 - lParam1); break;
		
		default: return 0;
	}
} 

void CFileDetailDialog::OnNMDblclkList(NMHDR *pNMHDR, LRESULT *pResult)
{
	TakeOver();
	*pResult = 0;
}

void CFileDetailDialog::OnNMRclickList(NMHDR *pNMHDR, LRESULT *pResult)
{
	CListCtrl* pmyListCtrl; 
	pmyListCtrl = (CListCtrl*)GetDlgItem(IDC_LISTCTRLFILENAMES);
	POINT point;
	::GetCursorPos(&point);
	CTitleMenu	popupMenu;


	UINT flag;
	flag=MF_STRING;
	if (pmyListCtrl->GetSelectionMark() == (-1)) flag=MF_GRAYED;

	popupMenu.CreatePopupMenu();
	popupMenu.AppendMenu(flag,MP_MESSAGE, GetResString(IDS_TAKEOVER));
	popupMenu.AppendMenu(MF_STRING,MP_RESTORE, GetResString(IDS_SV_UPDATE));
	popupMenu.TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, point.x, point.y, this);
	popupMenu.DestroyMenu();

	*pResult = 0;
}

BOOL CFileDetailDialog::OnCommand(WPARAM wParam,LPARAM lParam ){
	CListCtrl* pmyListCtrl; 
	pmyListCtrl = (CListCtrl*)GetDlgItem(IDC_LISTCTRLFILENAMES);
	if (pmyListCtrl->GetSelectionMark() != (-1)){

		switch (wParam)
		{
			case MP_MESSAGE:
			{
				TakeOver();
				return true;
			}
			case MP_RESTORE: {
				FillSourcenameList();
				return true;
			}
		}
	}
	if (wParam==2)
	{
		CDialog::OnOK();
		return TRUE;
	}

	return CDialog::OnCommand(wParam, lParam);
}

//For Comment// 
void CFileDetailDialog::OnBnClickedShowComment() 
{ 
   CCommentDialogLst dialog(m_file); 
   dialog.DoModal(); 
} 
//End for  comment// 

void CFileDetailDialog::Rename() 
{ 
   CString NewFileName; 
   GetDlgItem(IDC_FILENAME)->GetWindowText(NewFileName);

   m_file->SetFileName(NewFileName.GetBuffer()); 
   m_file->SavePartFile(); 

   GetDlgItem(IDC_FNAME)->SetWindowText(m_file->GetFileName());
   GetDlgItem(IDC_METFILE)->SetWindowText(m_file->GetFullName());
   GetDlgItem(IDC_FILENAME)->SetWindowText(m_file->GetFileName());
} 
