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


// ServerWnd.cpp : implementation file
//

#include "stdafx.h"
#include "emule.h"
#include "ServerWnd.h"
#include "HttpDownloadDlg.h"

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


// CServerWnd dialog

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

CServerWnd::~CServerWnd(){
}

BOOL CServerWnd::OnInitDialog(){
	CResizableDialog::OnInitDialog();

	imagelist.Create(16,16,ILC_COLOR8,2,2);
	imagelist.SetBkColor(::GetSysColor(COLOR_BTNFACE));
	imagelist.Add(theApp.LoadIcon(IDI_LOG));
	imagelist.Add(theApp.LoadIcon(IDI_SERVERINFO));
	StatusSelector.SetImageList(&imagelist);
	Localize();
	SetWindowLong(GetDlgItem(IDC_IPADDRESS)->m_hWnd,GWL_STYLE,WS_CHILD|WS_VISIBLE);
	SetWindowLong(GetDlgItem(IDC_IPADDRESS)->m_hWnd,GWL_EXSTYLE,WS_EX_STATICEDGE);
	serverlistctrl.Init(theApp.serverlist);
	
	m_ctrlNewServerFrm.Init(IDI_NEWSERVER);
	m_ctrlUpdateServerFrm.Init(IDI_UPDATESERVERS);
	m_ctrlMyInfo.Init(IDI_MYINFO);

	((CStatic*)GetDlgItem(IDC_SERVLST_ICO))->SetIcon((HICON)::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_SERVERLIST), IMAGE_ICON, 16, 16, 0));

	((CEdit*)GetDlgItem(IDC_SPORT))->SetLimitText(5);
	GetDlgItem(IDC_SPORT)->SetWindowText("4661");
	CRect rect;

	GetDlgItem(IDC_SERVMSG)->GetWindowRect(rect);
	::MapWindowPoints(NULL, m_hWnd, (LPPOINT)&rect, 2);
	servermsgbox.CreateEx(WS_EX_STATICEDGE,0,"MsgWnd",WS_VISIBLE | WS_CHILD | HTC_WORDWRAP |HTC_AUTO_SCROLL_BARS | HTC_UNDERLINE_HOVER,rect.left,rect.top,rect.Width(),rect.Height(),m_hWnd,0);
	
	servermsgbox.AppendText(CString(CString("eMule v")+CString(CURRENT_VERSION_LONG)+CString("\n")));
	servermsgbox.AppendText(GetResString(IDS_EMULEW)+CString(" "),false);
	CString strLink;
	// MOD Note: Do not remove this part - Merkur
	strLink.Format("http://vcheck.emule-project.net/en/version_check.php?version=%i&language=%i",CURRENT_VERSION_CHECK,theApp.glob_prefs->GetLanguageID());
	servermsgbox.AppendHyperLink(GetResString(IDS_EMULEW3)+CString(" "),0,strLink,0,false);
	servermsgbox.AppendText(GetResString(IDS_EMULEW2),false);
	// MOD Note: end
	servermsgbox.AppendText(CString("\n\n"));
	TCITEM newitem;
	CString name;
	name.Format("%s", GetResString(IDS_SV_SERVERINFO) );
	newitem.mask = TCIF_TEXT|TCIF_IMAGE;
	newitem.pszText = name.GetBuffer();
	newitem.cchTextMax = (int)name.GetLength()+1;
	newitem.iImage = 1;
	StatusSelector.InsertItem(StatusSelector.GetItemCount(),&newitem);
	name.Format("%s", GetResString(IDS_SV_LOG));
	newitem.mask = TCIF_TEXT|TCIF_IMAGE;
	newitem.pszText = name.GetBuffer();
	newitem.cchTextMax = (int)name.GetLength()+1;
	newitem.iImage = 0;
	StatusSelector.InsertItem(StatusSelector.GetItemCount(),&newitem);
	name="Debug";
	newitem.mask = TCIF_TEXT|TCIF_IMAGE;
	newitem.pszText = name.GetBuffer();
	newitem.cchTextMax = (int)name.GetLength()+1;
	newitem.iImage = 0;
	StatusSelector.InsertItem(StatusSelector.GetItemCount(),&newitem);
	
	AddAnchor(IDC_SERVLIST,TOP_LEFT, CSize(100,50));
	AddAnchor(servermsgbox, CSize(0,50), BOTTOM_RIGHT);
	AddAnchor(IDC_LOGBOX, CSize(0,50), BOTTOM_RIGHT);
	AddAnchor(IDC_DEBUG_LOG, CSize(0,50), BOTTOM_RIGHT);
	AddAnchor(IDC_SSTATIC,TOP_RIGHT);
	AddAnchor(IDC_SSTATIC4,TOP_RIGHT);
	AddAnchor(IDC_SSTATIC7,TOP_RIGHT);
	AddAnchor(IDC_IPADDRESS,TOP_RIGHT);
	AddAnchor(IDC_SSTATIC3,TOP_RIGHT);
	AddAnchor(IDC_SNAME,TOP_RIGHT);
	AddAnchor(IDC_ADDSERVER,TOP_RIGHT );
	AddAnchor(IDC_SBUTTON1,TOP_RIGHT);
	AddAnchor(IDC_SSTATIC5,TOP_RIGHT);
	AddAnchor(IDC_MYINFO,TOP_RIGHT ,CSize(100,50) );
	AddAnchor(IDC_MYINFOLIST,TOP_RIGHT,CSize(100,50));
	AddAnchor(IDC_SPORT,TOP_RIGHT);
	AddAnchor(IDC_SSTATIC6,TOP_RIGHT);
	AddAnchor(IDC_SERVERMETURL,TOP_RIGHT);
	AddAnchor(IDC_UPDATESERVERMETFROMURL,TOP_RIGHT);
	AddAnchor(IDC_LOGRESET,CSize(100,50));
	AddAnchor(IDC_TAB3,CSize(0,50), BOTTOM_RIGHT);
	debug = true;
	ToggleDebugWindow();

	servermsgbox.ShowWindow(SW_SHOW);
	debuglog.ShowWindow(SW_HIDE);
	logbox.ShowWindow(SW_HIDE);

	CString nameCountStr; 
	MyInfoList = (CMuleListCtrl*)GetDlgItem(IDC_MYINFOLIST); 
	if (MyInfoList->GetHeaderCtrl()->GetItemCount() < 2) { 
		MyInfoList->DeleteColumn(0); 
		MyInfoList->InsertColumn(0, "", LVCFMT_LEFT, 60, -1); 
		MyInfoList->InsertColumn(1, "", LVCFMT_LEFT, 132, 1); 
	}

	return true;
}

void CServerWnd::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_SERVLIST, serverlistctrl);
	//	DDX_Control(pDX, IDC_EDIT1, servermsgbox);

	DDX_Control(pDX, IDC_LOGBOX, logbox);
	DDX_Control(pDX, IDC_DEBUG_LOG, debuglog);
	DDX_Control(pDX, IDC_SSTATIC, m_ctrlNewServerFrm);
	DDX_Control(pDX, IDC_SSTATIC6, m_ctrlUpdateServerFrm);
	DDX_Control(pDX, IDC_MYINFO, m_ctrlMyInfo);
	DDX_Control(pDX, IDC_TAB3, StatusSelector);
}

bool CServerWnd::UpdateServerMetFromURL(CString strURL) {
	if ((strURL=="") || (strURL.Find("://") == -1))	// not a valid URL
	{
		theApp.emuledlg->AddLogLine(true, GetResString(IDS_INVALIDURL) );
		return false;
	}
	
	CString strTempFilename;
	strTempFilename.Format("%stemp-%d-server.met", theApp.glob_prefs->GetAppDir(), ::GetTickCount());

	// step2 - try to download server.met
	CHttpDownloadDlg dlgDownload;
	dlgDownload.m_sURLToDownload = strURL;
	dlgDownload.m_sFileToDownloadInto = strTempFilename;
	if (dlgDownload.DoModal() != IDOK)
	{
		theApp.emuledlg->AddLogLine(true, GetResString(IDS_ERR_FAILEDDOWNLOADMET), strURL);
		return false;
	}

	// step3 - add content of server.met to serverlis
	serverlistctrl.Hide();
	serverlistctrl.AddServermetToList(strTempFilename);
	serverlistctrl.Visable();
	remove(strTempFilename);
	return true;
}

void CServerWnd::Localize() {
	serverlistctrl.Localize();

	GetDlgItem(IDC_SERVLIST_TEXT)->SetWindowText(GetResString(IDS_SV_SERVERLIST));
	GetDlgItem(IDC_SSTATIC)->SetWindowText(GetResString(IDS_SV_NEWSERVER));
	GetDlgItem(IDC_SSTATIC4)->SetWindowText(GetResString(IDS_SV_ADDRESS));
	GetDlgItem(IDC_SSTATIC7)->SetWindowText(GetResString(IDS_SV_PORT));
	GetDlgItem(IDC_SSTATIC3)->SetWindowText(GetResString(IDS_SW_NAME));
	GetDlgItem(IDC_ADDSERVER)->SetWindowText(GetResString(IDS_SV_ADD));
	GetDlgItem(IDC_SSTATIC6)->SetWindowText(GetResString(IDS_SV_MET));
	GetDlgItem(IDC_UPDATESERVERMETFROMURL)->SetWindowText(GetResString(IDS_SV_UPDATE));
	GetDlgItem(IDC_LOGRESET)->SetWindowText(GetResString(IDS_PW_RESET));
	GetDlgItem(IDC_MYINFO)->SetWindowText(GetResString(IDS_MYINFO));
	TCITEM item;
	CString name;
	name.Format("%s", GetResString(IDS_SV_SERVERINFO) );
	item.mask = TCIF_TEXT;
	item.pszText = name.GetBuffer();
	item.cchTextMax = (int)name.GetLength()+1;
	StatusSelector.SetItem( 0, &item);
	name.Format("%s", GetResString(IDS_SV_LOG));
	item.mask = TCIF_TEXT;
	item.pszText = name.GetBuffer();
	item.cchTextMax = (int)name.GetLength()+1;
	StatusSelector.SetItem( 1, &item);
	name = "Debug";
	item.mask = TCIF_TEXT;
	item.pszText = name.GetBuffer();
	item.cchTextMax = (int)name.GetLength()+1;
	StatusSelector.SetItem( 2, &item);
}

BEGIN_MESSAGE_MAP(CServerWnd, CResizableDialog)
	ON_BN_CLICKED(IDC_ADDSERVER, OnBnClickedAddserver)
	ON_BN_CLICKED(IDC_UPDATESERVERMETFROMURL, OnBnClickedUpdateservermetfromurl)
	ON_BN_CLICKED(IDC_LOGRESET, OnBnClickedResetLog)
	ON_NOTIFY(TCN_SELCHANGE, IDC_TAB3, OnTcnSelchangeTab3)
END_MESSAGE_MAP()


// CServerWnd message handlers

void CServerWnd::OnBnClickedAddserver(){

	CString serveraddr;
	if (!GetDlgItem(IDC_IPADDRESS)->GetWindowTextLength()){
		theApp.emuledlg->AddLogLine(true, GetResString(IDS_SRV_ADDR) );
		return;
	}
	else
		GetDlgItem(IDC_IPADDRESS)->GetWindowText(serveraddr);

	if (!GetDlgItem(IDC_SPORT)->GetWindowTextLength()){
		theApp.emuledlg->AddLogLine(true, GetResString(IDS_SRV_PORT) );
		return;
	}

	char portstr[6];
	GetDlgItem(IDC_SPORT)->GetWindowText(portstr,6);
	CServer* toadd = new CServer(atoi(portstr),serveraddr.GetBuffer());

	// Barry - Default all manually added servers to high priority
	if( theApp.glob_prefs->GetManualHighPrio() )
		toadd->SetPreference(SRV_PR_HIGH);

	int32 namelen = GetDlgItem(IDC_SNAME)->GetWindowTextLength();
	if (namelen){
		char* servername = new char[namelen+2];
		GetDlgItem(IDC_SNAME)->GetWindowText(servername,namelen+1);
		toadd->SetListName(servername);
		delete[] servername;
	}
	else{
		toadd->SetListName(serveraddr.GetBuffer());
	}
	if (!serverlistctrl.AddServer(toadd,true)){
		CServer* update = theApp.serverlist->GetServerByAddress(toadd->GetAddress(), toadd->GetPort());
		if(update){
			update->SetListName(toadd->GetListName());
			serverlistctrl.RefreshServer(update);
		}
		delete toadd;
		theApp.emuledlg->AddLogLine(true, GetResString(IDS_SRV_NOTADDED) );
	} else theApp.emuledlg->AddLogLine(true,GetResString(IDS_SERVERADDED)+CString(toadd->GetListName()));
}

void CServerWnd::OnBnClickedUpdateservermetfromurl()
{
	// step1 - get url
	CString strURL;
	bool bDownloaded=false;
	GetDlgItem(IDC_SERVERMETURL)->GetWindowText(strURL);

	if (strURL==""){
		if (theApp.glob_prefs->adresses_list.IsEmpty()){
			theApp.emuledlg->AddLogLine(true, GetResString(IDS_SRV_NOURLAV) );
			return;
		}
		else
		{
			POSITION Pos = theApp.glob_prefs->adresses_list.GetHeadPosition(); 
			while ((!bDownloaded) && (Pos != NULL)){
				strURL = theApp.glob_prefs->adresses_list.GetNext(Pos).GetBuffer(); 
				bDownloaded=UpdateServerMetFromURL(strURL);
			}
		}
	}
	else
		UpdateServerMetFromURL(strURL);
}

void CServerWnd::OnBnClickedResetLog() {
	int cur_sel = StatusSelector.GetCurSel();
	if (cur_sel == (-1))
		return;
	if( cur_sel == 2 ){
		theApp.emuledlg->ResetDebugLog();
	}
	if( cur_sel == 1 ){
		theApp.emuledlg->ResetLog();
	}
	if( cur_sel == 0 ){
		servermsgbox.Clear();
	}
}
void CServerWnd::OnTcnSelchangeTab3(NMHDR *pNMHDR, LRESULT *pResult)
{
	*pResult = 0;
	int cur_sel = StatusSelector.GetCurSel();
	if (cur_sel == (-1))
		return;
	if( cur_sel == 2 ){
		debuglog.ShowWindow(SW_SHOW);
		servermsgbox.ShowWindow(SW_HIDE);
		logbox.ShowWindow(SW_HIDE);
	}
	if( cur_sel == 1 ){
		debuglog.ShowWindow(SW_HIDE);
		servermsgbox.ShowWindow(SW_HIDE);
		logbox.ShowWindow(SW_SHOW);
	}
	if( cur_sel == 0 ){
		debuglog.ShowWindow(SW_HIDE);
		servermsgbox.ShowWindow(SW_SHOW);
		logbox.ShowWindow(SW_HIDE);
	}
}

void CServerWnd::ToggleDebugWindow(){
	int cur_sel = StatusSelector.GetCurSel();
	if( theApp.glob_prefs->GetVerbose() && debug == false ){
		TCITEM newitem;
		CString name;
		name = "Debug";
		newitem.mask = TCIF_TEXT|TCIF_IMAGE;
		newitem.pszText = name.GetBuffer();
		newitem.cchTextMax = (int)name.GetLength()+1;
		newitem.iImage = 0;
		StatusSelector.InsertItem(StatusSelector.GetItemCount(),&newitem);
		debug = true;
	}
	else if( !theApp.glob_prefs->GetVerbose() && debug == true ) {
		if( cur_sel == 2 ){
			StatusSelector.SetCurSel(1);
			StatusSelector.SetFocus();
		}
		debuglog.ShowWindow(SW_HIDE);
		servermsgbox.ShowWindow(SW_HIDE);
		logbox.ShowWindow(SW_SHOW);
		StatusSelector.DeleteItem(2);
		debug = false;
	}
}

void CServerWnd::UpdateMyInfo() {
	CString buffer;

	MyInfoList->DeleteAllItems();
	MyInfoList->InsertItem(0,GetResString(IDS_STATUS)+":");
	if (theApp.serverconnect->IsConnected())
		MyInfoList->SetItemText(0, 1, GetResString(IDS_CONNECTED ));
	else MyInfoList->SetItemText(0, 1, GetResString(IDS_DISCONNECTED )); 

	if (theApp.serverconnect->IsConnected()) {
		MyInfoList->InsertItem(1,GetResString(IDS_IP) +":"+GetResString(IDS_PORT) );
		if (theApp.serverconnect->IsLowID()) buffer=GetResString(IDS_UNKNOWN); else {
			uint32 myid=theApp.serverconnect->GetClientID();
			uint8 d=myid/(256*256*256);myid-=d*(256*256*256);
			uint8 c=myid/(256*256);myid-=c*256*256;
			uint8 b=myid/(256);myid-=b*256;
			buffer.Format("%i.%i.%i.%i:%i",myid,b,c,d,theApp.glob_prefs->GetPort());
		}
		MyInfoList->SetItemText(1,1,buffer);

		buffer.Format("%u",theApp.serverconnect->GetClientID());
		MyInfoList->InsertItem(2,GetResString(IDS_ID));
		if (theApp.serverconnect->IsConnected()) MyInfoList->SetItemText(2, 1, buffer); 

		MyInfoList->InsertItem(3,"");
		if (theApp.serverconnect->IsLowID()) MyInfoList->SetItemText(3, 1,GetResString(IDS_IDLOW));
			else MyInfoList->SetItemText(3, 1,GetResString(IDS_IDHIGH));
	}
}