// This file is a part of the xMule Project.
//
// Copyright (c) 2004 Theodore R. Smith (hopeseekr@xmule.ws / http://www.xmule.ws/)
// DSA-1024 Fingerprint: 10A0 6372 9092 85A2 BB7F 907B CB8B 654B E33B F1ED
//
//Copyright (C)2002 Merkur ( merkur-@users.sourceforge.net / http://www.xmule-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.

#ifdef PRECOMP
#	include "xmule-headers.h"
#else
#	include "config.h"
#	include "HTTPDownloadDlg.h"
#	include "muuli_wdr.h"
#	include "ServerWnd.h"
#	include "wintypes.h"
#	include "xmule.h"
#	include "xmuleDlg.h"
#endif
#include "otherfunctions.h"                 // GetResString
#include "ServerList.h"                     // CServerList
#include "ServerListCtrl.h"                 // CServerListCtrl


#include <DynPrefs/DynPrefs.h>              // Needed for DynamicPreferences

#include <wx/settings.h>
#include <wx/sizer.h>                       // Needed for wxSizer

//IMPLEMENT_DYNAMIC(CServerWnd, CDialog)
IMPLEMENT_DYNAMIC_CLASS(CServerWnd, wxPanel)

BEGIN_EVENT_TABLE(CServerWnd, wxPanel)
EVT_BUTTON(ID_ADDTOLIST, CServerWnd::OnBnClickedAddserver)
EVT_BUTTON(ID_UPDATELIST, CServerWnd::OnBnClickedUpdateservermetfromurl)
EVT_BUTTON(ID_BTN_RESET, CServerWnd::OnBnClickedResetLog)
END_EVENT_TABLE()

#include <wx/textctrl.h>

    CServerWnd::CServerWnd(wxWindow *pParent /*=NULL*/

)
: wxPanel(pParent, CServerWnd::IDD)
{
    SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
    wxSizer *content = serverListDlg(this, TRUE);
    content->Show(this, TRUE);
    // init serverlist
    // no use now. too early.
    CServerListCtrl *list = (CServerListCtrl *) wxFindWindowByName("serverListCtrl");
    //list->Init(theApp.serverlist);
    serverlistctrl = list;
    wxTextCtrl *cv = (wxTextCtrl *) FindWindowByName("serverInfo");
    cv->AppendText(wxString(_("This is ")) + wxString("xMule") + wxString(" ") + PACKAGE_VERSION + wxString(_(" (based on ")) + wxString(_("eMule")) + wxString(")\n"));
    cv->AppendText(wxString(_("Visit http://www.xmule.ws/ to check if a new version is available.\n")));
    //  cv->AppendText(GetResString(IDS_EMULEW)+wxString(" "));
    //  cv->AppendText(GetResString(IDS_EMULEW3)+wxString(" "));
    //  cv->AppendText(GetResString(IDS_EMULEW2)+wxString("\n\n"));
}

CServerWnd::~CServerWnd()
{
}

#if 0
bool CServerWnd::OnInitDialog()
{
    CResizableDialog::OnInitDialog();
    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));
    ((CStatic *) GetDlgItem(IDC_SERVINF_ICO))->SetIcon((HICON)::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_SERVERINFO), IMAGE_ICON, 16, 16, 0));
    ((CStatic *) GetDlgItem(IDC_LOG_ICO))->SetIcon((HICON)::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_LOG), 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(wxString(wxString("xMule v") + wxString(CURRENT_VERSION_LONG) + wxString("\n")));
    servermsgbox.AppendText(GetResString(IDS_EMULEW) + wxString(" "), false);
    wxString strLink;
    strLink.Printf("http://www.xmule-project.net/en/version_check.php?version=%i&language=%i", CURRENT_VERSION_CHECK, theApp.glob_prefs->GetLanguageID());
    servermsgbox.AppendHyperLink(GetResString(IDS_EMULEW3) + wxString(" "), 0, strLink, 0, false);
    servermsgbox.AppendText(GetResString(IDS_EMULEW2), false);
    servermsgbox.AppendText(wxString("\n\n"));
    AddAnchor(IDC_SERVLIST, TOP_LEFT, CSize(100, 34));
    AddAnchor(IDC_SERVINF_TEXT, CSize(0, 34));
    AddAnchor(IDC_SERVINF_ICO, CSize(0, 34));
    AddAnchor(servermsgbox, CSize(0, 34), CSize(100, 60));
    AddAnchor(IDC_LOG_TEXT, CSize(0, 60));
    AddAnchor(IDC_LOG_ICO, CSize(0, 60));
    AddAnchor(IDC_LOGBOX, CSize(0, 60), 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, 60));
    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_SSTATIC, m_ctrlNewServerFrm);
    DDX_Control(pDX, IDC_SSTATIC6, m_ctrlUpdateServerFrm);
}

#endif

void CServerWnd::UpdateServerMetFromURL(wxString strURL)
{
    // not a valid URL:
    if (strURL.Find("://") == - 1)
    {
        theApp.xmuledlg->AddLogLine(true, GetResString(IDS_INVALIDURL));
        return;
    }
    wxString strTempFilename;
    strTempFilename.Printf(theApp.dynprefs->Get<wxString>("app-directory") + wxT("temp-%d-server.met"), ::GetTickCount());
    CHTTPDownloadDlg *dlg = new CHTTPDownloadDlg(this, strURL, strTempFilename);
    int retval = dlg->ShowModal();
    if (retval == 0)
    {
        // wget succeeded. proceed with serverlist processing
        serverlistctrl->AddServermetToList(strTempFilename);
        wxRemoveFile(strTempFilename);
        theApp.serverlist->SaveServermetToFile();
    }
    else
    {
        theApp.xmuledlg->AddLogLine(true, GetResString(IDS_ERR_FAILEDDOWNLOADMET) .GetData(), strURL.GetData());
    }
    delete dlg;
#if 0
    // step2 - try to download server.met
    CHttpDownloadDlg dlgDownload;
    dlgDownload.m_sURLToDownload = strURL;
    dlgDownload.m_sFileToDownloadInto = strTempFilename;
    if (dlgDownload.DoModal() != IDOK)
    {
        theApp.xmuledlg->AddLogLine(true, GetResString(IDS_ERR_FAILEDDOWNLOADMET), strURL);
        return;
    }
    // step3 - add content of server.met to serverlis
    serverlistctrl.Hide();
    serverlistctrl.AddServermetToList(strTempFilename);
    serverlistctrl.Visable();
    wxRemoveFile(strTempFilename);
    theApp.serverlist->SaveServermetToFile();
#endif
}

void CServerWnd::Localize()
{
#if 0
    serverlistctrl.Localize();
    GetDlgItem(IDC_SERVLIST_TEXT)->SetWindowText(GetResString(IDS_SV_SERVERLIST));
    GetDlgItem(IDC_SERVINF_TEXT)->SetWindowText(GetResString(IDS_SV_SERVERINFO));
    GetDlgItem(IDC_LOG_TEXT)->SetWindowText(GetResString(IDS_SV_LOG));
    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));
#endif
}

#if 0
BEGIN_MESSAGE_MAP(CServerWnd, CResizableDialog)
ON_BN_CLICKED(IDC_ADDSERVER, OnBnClickedAddserver)
ON_BN_CLICKED(IDC_UPDATESERVERMETFROMURL, OnBnClickedUpdateservermetfromurl)
ON_BN_CLICKED(IDC_LOGRESET, OnBnClickedResetLog)
END_MESSAGE_MAP()

#endif
// CServerWnd message handlers

void CServerWnd::OnBnClickedAddserver(wxCommandEvent &evt)
{
    wxString serveraddr;
    if (((wxTextCtrl *) FindWindowByName("ipAddress"))->GetLineText(0) .IsEmpty())
    {
        //if (!GetDlgItem(IDC_IPADDRESS)->GetWindowTextLength()){
        theApp.xmuledlg->AddLogLine(true, GetResString(IDS_SRV_ADDR));
        return;
    }
    else
    serveraddr = ((wxTextCtrl *) FindWindowByName("ipAddress"))->GetLineText(0);
    //GetDlgItem(IDC_IPADDRESS)->GetWindowText(serveraddr);
    //if (!GetDlgItem(IDC_SPORT)->GetWindowTextLength()){
    if (((wxTextCtrl *) FindWindowByName("portNumber"))->GetLineText(0) .IsEmpty())
    {
        theApp.xmuledlg->AddLogLine(true, GetResString(IDS_SRV_PORT));
        return;
    }
    //char portstr[6];
    //GetDlgItem(IDC_SPORT)->GetWindowText(portstr,6);
    wxString portstr;
    portstr = ((wxTextCtrl *) FindWindowByName("portNumber"))->GetLineText(0);
    CServer *toadd = new CServer(atoi(portstr.GetData()), (char *) serveraddr.GetData());
    //int32_t namelen = GetDlgItem(IDC_SNAME)->GetWindowTextLength();
    wxString servername;
    servername = ((wxTextCtrl *) FindWindowByName("serverName"))->GetLineText(0);
    if (!servername.IsEmpty())
    {
        //char* servername = new char[namelen+2];
        //GetDlgItem(IDC_SNAME)->GetWindowText(servername,namelen+1);
        toadd->SetListName((char *) servername.GetData());
        //delete[] servername;
    }
    else
    {
        toadd->SetListName((char *) serveraddr.GetData());
    }
    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.xmuledlg->AddLogLine(true, GetResString(IDS_SRV_NOTADDED));
    }
    else theApp.xmuledlg->AddLogLine(true, GetResString(IDS_SERVERADDED) + "%s", toadd->GetListName());
    theApp.serverlist->SaveServermetToFile();
}

void CServerWnd::OnBnClickedUpdateservermetfromurl(wxCommandEvent &evt)
{
    wxString strURL;
    strURL = ((wxTextCtrl *) FindWindowByName("serverlistURL"))->GetLineText(0);
    UpdateServerMetFromURL(strURL);
}

void CServerWnd::OnBnClickedResetLog(wxCommandEvent &evt)
{
    theApp.xmuledlg->ResetLog();
}

void CServerWnd::UpdateMyInfo()
{
#if 0
    wxString 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_t myid = theApp.serverconnect->GetClientID();
            uint8_t d = myid/ (256 *256 *256);
            myid -= d * (256 *256 *256);
            uint8_t c = myid/ (256 *256);
            myid -= c *256 *256;
            uint8_t b = myid/ (256);
            myid -= b *256;
            buffer.Printf("%i.%i.%i.%i:%i", myid, b, c, d, theApp.glob_prefs->GetPort());
        }
        MyInfoList->SetItemText(1, 1, buffer);
        buffer.Printf("%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));
    }
#endif
    //	printf("TODO: MyInfo @ CServerWnd (GUI missing)\n");
}

