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


// 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_COLOR32 ,0,10);
	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);
	((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_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);

	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_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);
	theApp.serverlist->SaveServermetToFile();
	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));
	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()));
	theApp.serverlist->SaveServermetToFile();
}

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.SetWindowText( "" );
	}
}
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;
	}
}
