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

#ifdef PRECOMP
    #include "xmule-headers.h"
#endif

#include "xmuleDlg.h"                       // Needed for this Interface's Prototype

#include "AddFileThread.h"                  // Needed for CAddFileThread
#include "ChatWnd.h"                        // Needed for CChatWnd
#include "ClientCredits.h"                  // Needed for CClientCredits
#include "ClientList.h"                     // Needed for CClientList
#include "ClientUDPSocket.h"                // Needed for CClientUDPSocket
#include "config.h"                         // Needed for PACKAGE_NAME
#include "DownloadListCtrl.h"               // Needed for CDownloadListCtrl
#include "DownloadQueue.h"                  // Needed for CDownloadQueue
#include "FriendList.h"                     // Needed for CFriendList
#include "KnownFileList.h"                  // Needed for CKnownFileList
#include "ldaemon.h"                        // Needed for CLDaemon
#include "ListenSocket.h"                   // Needed for CListenSocket
#include "muuli_wdr.h"                      // Needed for ID_BUTTONCONNECT
#include "NewSockets.h"                     // Needed for NewSocket_Stop
#include "opcodes.h"                        // Needed for ID_XMULEDLG
#include "PartFile.h"                       // Needed for CPartFile
#include "Preferences.h"                    // Needed for CPreferences
#include "PreferencesDlg.h"                 // Needed for CPreferencesDlg
#include "QueueListCtrl.h"                  // Needed for CQueueListCtrl
#include "SearchDlg.h"                      // Needed for CSearchDlg
#include "server.h"                         // Needed for CServer
#include "ServerList.h"                     // Needed for CServerList
#include "ServerListCtrl.h"                 // Needed for CServerListCtrl
#include "ServerSocket.h"                   // Needed for CServerSocket
#include "ServerWnd.h"                      // Needed for CServerWnd
#include "SharedFileList.h"                 // Needed for CSharedFileList
#include "SharedFilesCtrl.h"                // Needed for CSharedFilesCtrl
#include "SharedFilesWnd.h"                 // Needed for CSharedFilesWnd
#include "sockets.h"                        // Needed for CServerConnect
#include "StatisticsDlg.h"                  // Needed for CStatisticsDlg
#include "SysTray.h"                        // Needed for CSysTray
#include "TransferWnd.h"                    // Needed for CTransferWnd
#include "UDPSocket.h"                      // Needed for CUDPSocket
#include "UploadListCtrl.h"                 // Needed for CUploadListCtrl
#include "UploadQueue.h"                    // Needed for CUploadQueue
#include "xmule.h"                          // Needed for theApp

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

#include <cerrno>                           // Needed for errno
#include <cmath>                            // Needed for ceil
#include <signal.h>                         // Needed for SIGPIPE
#include <arpa/inet.h>                      // Needed for inet_addr

#include <wx/config.h>                      // Needed for wxConfigBase
#include <wx/msgdlg.h>                      // Needed for wxMessageBox
#include <wx/radiobut.h>                    // Needed for wxRadioButton
#include <wx/sizer.h>                       // Needed for wxSizer::Show
#include <wx/splitter.h>                    // Needed for wxSplitterWindow
#include <wx/stattext.h>                    // Needed for wxStaticText
#include <wx/textctrl.h>                    // Needed for wxTextCtrl

// connection images
#include "pixmaps/mule_TrayIcon.ico.xpm"
#include "pixmaps/mule_Tr_yellow.ico.xpm"
#include "pixmaps/mule_Tr_grey.ico.xpm"

#if wxMINOR_VERSION > 4
    #define CLOSEBOX wxCLOSE_BOX
#else
    #define CLOSEBOX 0
#endif

#define ID_UQTIMER 59742
#define TM_DNSDONE 17851

extern wxRadioButton* radiobutton[4];

BEGIN_EVENT_TABLE(CxmuleDlg, wxFrame)
    EVT_SOCKET(ID_SOKETTI, CxmuleDlg::socketHandler)
    EVT_TOOL(ID_BUTTONCONNECT, CxmuleDlg::OnBnConnect)
    EVT_TOOL(ID_BUTTONPREFERENCES, CxmuleDlg::btnPreferences)
    EVT_TOOL(ID_BUTTONSERVERS, CxmuleDlg::OnToolClick)
    EVT_TOOL(ID_BUTTONSEARCH, CxmuleDlg::OnToolClick)
    EVT_TOOL(ID_BUTTONTRANSFER, CxmuleDlg::OnToolClick)
    EVT_TOOL(ID_BUTTONSHARED, CxmuleDlg::OnToolClick)
    EVT_TOOL(ID_BUTTONMESSAGES, CxmuleDlg::OnToolClick)
    EVT_TOOL(ID_BUTTONSTATISTICS, CxmuleDlg::OnToolClick)
    EVT_TOOL(ID_BUTTONFLOWCHART, CxmuleDlg::OnToolClick)
    EVT_TIMER(ID_UQTIMER, CxmuleDlg::OnUQTimer)
    EVT_TIMER(4322, CxmuleDlg::OnUDPTimer)
    EVT_TIMER(4333, CxmuleDlg::OnSocketTimer)
    EVT_MENU(TM_FINISHEDHASHING, CxmuleDlg::OnFinishedHashing)
    EVT_MENU(TM_DNSDONE, CxmuleDlg::OnDnsDone)
    EVT_CLOSE(CxmuleDlg::OnClose)
    EVT_MENU(TM_HASHTHREADFINISHED, CxmuleDlg::OnHashingShutdown)
    EVT_ICONIZE(CxmuleDlg::MinimizeDlg)
END_EVENT_TABLE()

void CxmuleDlg::OnDnsDone(wxCommandEvent & evt)
{
    CUDPSocket * socket = (CUDPSocket *) evt.GetClientData();
    struct sockaddr_in * si = (struct sockaddr_in *) evt.GetInt();
    socket->DnsLookupDone(si);
}

void CxmuleDlg::OnFinishedHashing(wxCommandEvent & evt)
{
    //wxMutexGuiEnter();
    //(CKnownFile*)lParam;:
    CKnownFile * result = (CKnownFile *) evt.GetClientData();
    if (evt.GetInt())
    {
        //wParam;:
        CPartFile * requester = (CPartFile *) evt.GetInt();
        requester->PartFileHashFinished(result);
    }
    else
    {
        if (theApp.sharedfiles->filelist->SafeAddKFile(result))
        {
            theApp.sharedfiles->SafeAddKFile(result);
        }
        else
        {
            delete result;
        }
    }
    //wxMutexGuiLeave();
    return;
}

void muleDefaultToolbar(wxToolBar * parent)
{
    parent->SetMargins(2, 2);
    // First of all, create bar with the Disconnect button
    parent->AddTool(ID_BUTTONCONNECT, _("Connect"), connButImg(0), _("Connect to server"));
    parent->AddSeparator();
    parent->AddCheckTool(ID_BUTTONSERVERS, _("Servers"), xmuleDlgImages(3), wxNullBitmap, _("Server list"));
    parent->AddCheckTool(ID_BUTTONSEARCH, _("Search"), xmuleDlgImages(2), wxNullBitmap, _("Search files"));
    parent->AddCheckTool(ID_BUTTONTRANSFER, _("Transfer"), xmuleDlgImages(1), wxNullBitmap, _("File transfer"));
    parent->AddCheckTool(ID_BUTTONSHARED, _("Shared Files"), xmuleDlgImages(18), wxNullBitmap, _("Show shared files"));
    parent->AddCheckTool(ID_BUTTONMESSAGES, _("Messages"), xmuleDlgImages(21), wxNullBitmap, _("Messages"));
    //    parent->AddCheckTool( ID_BUTTONIRC, _("IRC"),xmuleDlgImages( 19 ), wxNullBitmap, _("Internet Relay Chat"));
    parent->AddCheckTool(ID_BUTTONSTATISTICS, _("Statistics"), xmuleDlgImages(4), wxNullBitmap, _("Show current statistics"));
    parent->AddSeparator();
    parent->AddTool(ID_BUTTONFLOWCHART, _("Main Prefs"), xmuleDlgImages(5), _("Most setings"));
    parent->AddTool(ID_BUTTONPREFERENCES, _("Minor Prefs"), xmuleDlgImages(6), _("Modify preferences"));
    parent->AddSeparator();
    parent->Realize();
}

// CxmuleDlg Dialog

CxmuleDlg::CxmuleDlg(wxWindow * pParent, wxString title)
: wxFrame(pParent, ID_XMULEDLG, title, wxDefaultPosition, wxSize(800, 520),
wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxTHICK_FRAME | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | CLOSEBOX)
{
    OnInit();
}

void CxmuleDlg::OnInit()
{
    theApp.xmuledlg = this;
    m_app_state = APP_STATE_STARTING;
    srand(time(NULL));
    // get rid of sigpipe
    signal(SIGPIPE, SIG_IGN);
    //: CTrayDialog(CxmuleDlg::IDD, pParent){
    wxSizer * dlg = muleDlg(this, false, true);
    serverwnd = new CServerWnd(this);
    searchwnd = new CSearchDlg(this);
    transferwnd = new CTransferWnd(this);
    preferenceswnd = new CPreferencesDlg(this, theApp.glob_prefs);
    sharedfileswnd = new CSharedFilesWnd(this);
    statisticswnd = new CStatisticsDlg(this);
    chatwnd = new CChatWnd(this);
    transicons[0] = dlStatusImages(0);
    transicons[1] = dlStatusImages(1);
    transicons[2] = dlStatusImages(2);
    transicons[3] = dlStatusImages(3);
#define ID_BITMAPBUTTON (-1)
    wxToolBar * newbar = new wxToolBar(this, - 1, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL | wxNO_BORDER | wxTB_TEXT);
    muleDefaultToolbar(newbar);
    //buttonToolbar->Add(newbar,0,wxGROW|wxALL,5);
    //buttonToolbar->Layout();
    m_wndToolbar = newbar;
    // initially server page is visible
    m_wndToolbar->ToggleTool(ID_BUTTONSERVERS, TRUE);
    lastbutton = ID_BUTTONSERVERS;
    // these are not implemented
    m_wndToolbar->EnableTool(ID_BUTTONIRC, FALSE);
    //m_wndToolbar->EnableTool(ID_BUTTONMESSAGES,FALSE);
    dlg->Show(this, TRUE);
    contentSizer->Add(serverwnd, 1, wxALIGN_LEFT | wxEXPAND | wxALL, 5);
    serverwnd->Show(FALSE);
    activewnd = serverwnd;
    searchwnd->Show(FALSE);
    transferwnd->Show(FALSE);
    sharedfileswnd->Show(FALSE);
    statisticswnd->Show(FALSE);
    chatwnd->Show(FALSE);
    SetActiveDialog(serverwnd);
    m_nActiveDialog = 1;
    // can't init now
    //theApp.serverlist->Init();
 /* Razor 1a - Modif by MikaelB
    Set client size and position */
    // Create a config base for saving razor preferences
    wxConfigBase * config = wxConfigBase::Get();
    // If config haven't been created
    if (config == NULL)
    // exit without saving
    return;
    // The section where to save in in file
    wxString section = "/Razor_Preferences/";
    // Main window location and size
    int x1, y1, x2, y2;
    // Saving window size and position
    x1 = config->Read(_T(section + "MAIN_X_POS"), 0l);
    y1 = config->Read(_T(section + "MAIN_Y_POS"), 0l);
    x2 = config->Read(_T(section + "MAIN_X_SIZE"), 0l);
    y2 = config->Read(_T(section + "MAIN_Y_SIZE"), 0l);
    split_pos = config->Read(_T(section + "SPLITTER_POS"), 0l);
    // If x1 and y1 != 0
    if ((x1 != 0) && (y1 != 0))
    // Redefine location
    Move(x1, y1);
    // If x2 and y2 != 0
    if ((x2 != 0) && (y2 != 0))
    // Redefine size
    SetClientSize(x2, y2);
    /* End modif */
    // Modified tool bar integration... should not have any problems about cut Preferences button
    SetToolBar(newbar);
    CAddFileThread::Setup();
}

class QueryDlg: public wxDialog
{
public:
    QueryDlg(wxWindow* parent): wxDialog(parent, 21373, _("Desktop integration"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxSYSTEM_MENU)
    {
        wxSizer* content = desktopDlg(this, TRUE);
        content->Show(this, TRUE);
        Centre();
    }
protected:
    void OnOk(wxCommandEvent& evt)
    {
        long mode = 0;

        if (radiobutton[0]->GetValue())
        {
            mode = 1;
        }
        else if (radiobutton[1]->GetValue())
        {
            mode = 2;
        }
        else if (radiobutton[2]->GetValue())
        {
            mode = 3;
        }
        else
        {
            mode = 4;
        }

        theApp.dynprefs->Add("systray-integration", mode);
        EndModal(0);
    }
    DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(QueryDlg, wxDialog)
    EVT_BUTTON(ID_OK, QueryDlg::OnOk)
END_EVENT_TABLE()

void CxmuleDlg::changeDesktopMode()
{
    QueryDlg query(this);
}

void CxmuleDlg::createSystray(const wxString & title)
{
    // create the docklet (at this point we already have preferences!)
    if (theApp.dynprefs->Get<long>("systray-integration") == 0)
    {
        // ok, it's not set yet.
        changeDesktopMode();
    }

    m_wndTaskbarNotifier = new CSysTray(this, theApp.dynprefs->Get<long>("systray-integration"), title);
}

extern void TimerProc();

void CxmuleDlg::OnUQTimer(wxTimerEvent & evt)
{
    // call timerproc
    if (!IsRunning())
    {
        return;
    }
    TimerProc();
}

void CxmuleDlg::InitDialog()
{
    theApp.serverlist->Init();
}

bool CxmuleDlg::IsRunning()
{
    return(m_app_state == APP_STATE_RUNNING);
}
#include <iostream>
void CxmuleDlg::OnToolClick(wxCommandEvent& event)
{
    int id = event.GetId();

    if (id == ID_BUTTONCONNECT)
    {
        wxCommandEvent temp_event;
        OnBnConnect(temp_event);
    }
    else if (id == ID_BUTTONPREFERENCES)
    {
        preferenceswnd->ShowModal();
    }
    else if (id == lastbutton)
    {
        return;
    }


    m_wndToolbar->ToggleTool(lastbutton, FALSE);
    lastbutton = id;

    switch(id)
    {
        case ID_BUTTONSERVERS: SetActiveDialog(serverwnd); m_nActiveDialog = 1; break;
        case ID_BUTTONSEARCH: SetActiveDialog(searchwnd); m_nActiveDialog = 3; break;
        case ID_BUTTONTRANSFER: SetActiveDialog(transferwnd); m_nActiveDialog = 2; break;
        case ID_BUTTONSHARED: SetActiveDialog(sharedfileswnd); m_nActiveDialog = 4; break;
        case ID_BUTTONMESSAGES: SetActiveDialog(chatwnd); m_nActiveDialog = 5; break;
        case ID_BUTTONSTATISTICS: SetActiveDialog(statisticswnd); m_nActiveDialog = 6; break;
        case ID_BUTTONFLOWCHART: SetActiveDialog((wxWindow *)flowchartwnd); m_nActiveDialog = 7; break;
        default: break;
    };
    theApp.SetCompatiblePrefs();    
    // UpdateBar();
}

void CxmuleDlg::btnPreferences(wxCommandEvent& ev)
{
    theApp.SetCompatiblePrefs();
    // do preferences
    preferenceswnd->ShowModal();
}

void CxmuleDlg::socketHandler(wxSocketEvent& event)
{
    cout << "CxmuleDlg::socketHandler() should have *not* been called! :o" << endl;
}

CxmuleDlg::~ CxmuleDlg()
{
    ShutDown();
}

void CxmuleDlg::ShutDown()
{
    printf("Shutting down xMule...\n");
 /* Razor 1a - Modif by MikaelB
    Save client size and position */
    // Create a config base for saving razor preferences
    wxConfigBase * config = wxConfigBase::Get();
    // If config haven't been created
    if (config == NULL)
    // exit without saving
    return;
    // The section where to save in in file
    wxString section = "/Razor_Preferences/";
    // Main window location and size
    int x1, y1, x2, y2;
    GetPosition( & x1, & y1);
    GetSize( & x2, & y2);
    // Saving window size and position
    config->Write(_T(section + "MAIN_X_POS"), (long) x1);
    config->Write(_T(section + "MAIN_Y_POS"), (long) y1);
    config->Write(_T(section + "MAIN_X_SIZE"), (long) x2);
    config->Write(_T(section + "MAIN_Y_SIZE"), (long) y2);
    // Saving sash position of splitter in transfer window
    wxSplitterWindow * split = (wxSplitterWindow *) FindWindow("splitterWnd");
    config->Write(_T(section + "SPLITTER_POS"), (long) split_pos);
    config->Flush(true);
    /* End modif */
    theApp.OnlineSig(true);
    // TODO: We want to free the memory used by the webserver
    //       but currently it does wait in accept().
    // delete theApp.webserver;
    delete theApp.serverlist;
    theApp.serverlist = NULL;
    delete theApp.clientcredits;
    theApp.clientcredits = NULL;
    // Destroying CDownloadQueue calls destructor for CPartFile
    // calling CSharedFileList::SafeAddKFile occasally.
    delete theApp.downloadqueue;
    theApp.downloadqueue = NULL;
    delete theApp.sharedfiles;
    theApp.sharedfiles = NULL;
    delete theApp.knownfiles;
    theApp.knownfiles = NULL;
    delete theApp.uploadqueue;
    theApp.uploadqueue = NULL;
    delete theApp.clientlist;
    theApp.clientlist = NULL;
    delete theApp.friendlist;
    theApp.friendlist = NULL;
    delete theApp.glob_prefs;
    theApp.glob_prefs = NULL;
    delete theApp.serverconnect;
    theApp.serverconnect = NULL;
    delete m_wndTaskbarNotifier;
    m_wndTaskbarNotifier = NULL;
}

// CxmuleDlg eventhandler

void CxmuleDlg::OnBnConnect(wxCommandEvent& event)
{
    if (!theApp.serverconnect->IsConnected())
    //connect if not currently connected
    if (!theApp.serverconnect->IsConnecting()) StartConnection();
    else
    {
        theApp.serverconnect->StopConnectionTry();
        ShowConnectionState(false);
    }
    else
    {
        //disconnect if currently connected
        CloseConnection();
    }
    // UpdateBar();
}

void CxmuleDlg::ResetLog()
{
    logtext = "";
    //serverwnd.logbox.SetWindowText(logtext);
    wxTextCtrl * ct = (wxTextCtrl *) serverwnd->FindWindowByName("logView");
    if (ct)
    {
        ct->SetValue("");
    }
    // Delete log file aswell.
    wxRemoveFile(wxString::Format("%s/.xMule/logfile", getenv("HOME")));
}

void CxmuleDlg::ResetDebugLog()
{
    logtext = "";
    //SetWindowText(logtext);:
}

void CxmuleDlg::AddLogLine(bool addtostatusbar, const wxChar * line, ...)
{
    //<<--9/21/02:
    char osDate[30], osTime[30];
    //<<--9/21/02:
    char temp[1060];
    char bufferline[1000];
    va_list argptr;
    va_start(argptr, line);
    vsnprintf(bufferline, 1000, line, argptr);
    va_end(argptr);
    if (addtostatusbar)
    {
        //  statusbar.SetStatusText(bufferline,0); //,0);
        wxStaticText * text = (wxStaticText *) FindWindow("infoLabel");
        text->SetLabel(bufferline);
        Layout();
    }
    time_t joskus = time(NULL);
    struct tm * nyt = localtime( & joskus);
    strftime(osDate, 29, "%F", nyt);
    strftime(osTime, 29, "%T", nyt);
    //strtime( osTime ); //<<--9/21/02
    //strdate( osDate ); //<<--9/21/02
    //<<--9/21/02:
    sprintf(temp, "%s %s: %s\n", osDate, osTime, bufferline);
    wxTextCtrl * ct = (wxTextCtrl *) serverwnd->FindWindowByName("logView");
    if (ct)
    {
        ct->AppendText(temp);
        //ct->ShowPosition(ct->GetLastPosition());
        ct->ShowPosition(ct->GetValue() .Length() - 1);
    }
    // Write into log file
    wxString filename;
    filename =  wxString(getenv("HOME"), *wxConvCurrent) + wxT("/.xMule/logfile");
    wxFile file(filename, wxFile::write_append);
    if (file.IsOpened())
    {
        file.Write(temp);
        file.Close();
    }
    //printf("***LOG: %s\n",logtext);
}

void CxmuleDlg::AddServerMessageLine(char * line, ...)
{
    wxString content;
    va_list argptr;
    char bufferline[500];
    va_start(argptr, line);
    vsnprintf(bufferline, 500, line, argptr);
    va_end(argptr);
    wxTextCtrl * cv = (wxTextCtrl *) serverwnd->FindWindowByName("serverInfo");
    if (cv)
    {
        cv->AppendText(wxString(bufferline) + wxString("\n"));
        cv->ShowPosition(cv->GetValue() .Length() - 1);
    }
    //serverwnd.servermsgbox.AppendText(wxString(bufferline)+wxString("\n"));
}

void CxmuleDlg::ShowConnectionState(bool connected)
{
    ShowConnectionState(connected, "");
}

#define STAT_LOWID 1
#define STAT_HIGHID 2
#define STAT_CONNECTING 3
#define STAT_NOTCONNECTED 4

void CxmuleDlg::ShowConnectionState(bool connected, wxString server, bool iconOnly)
{
    static int __oldstatus = ( - 1);
    bool changed = false;
    serverwnd->UpdateMyInfo();
    if (connected)
    {
        wxStaticBitmap * bmp = (wxStaticBitmap *) FindWindowByName("connImage");
        if (theApp.serverconnect->IsLowID())
        {
            if (__oldstatus != STAT_LOWID)
            {
                bmp->SetBitmap(connImages(1));
                __oldstatus = STAT_LOWID;
                changed = true;
            }
        }
        else
        {
            if (__oldstatus != STAT_HIGHID)
            {
                bmp->SetBitmap(connImages(3));
                __oldstatus = STAT_HIGHID;
                changed = true;
            }
        }
        //butn->SetLabel(GetResString(IDS_MAIN_BTN_DISCONNECT));
        //butn->SetDefaultBitmap(connButImg(1));
        // we can't modify existing button. so we delete the old and create a new one
        if (changed)
        {
            m_wndToolbar->DeleteTool(ID_BUTTONCONNECT);
            m_wndToolbar->InsertTool(0, ID_BUTTONCONNECT, GetResString(IDS_MAIN_BTN_DISCONNECT), connButImg(1), GetResString(IDS_MAIN_BTN_DISCONNECT_TOOLTIP));
            m_wndToolbar->Realize();
        }
 /*
 this->GetDlgItem(IDC_BUTTON2)->SetWindowText(GetResString(IDS_MAIN_BTN_DISCONNECT));
 m_btnConnect.SetIcon(IDI_BN_DISCONNECT); m_btnConnect.SetTooltipText(GetResString(IDS_MAIN_BTN_DISCONNECT_TOOLTIP));
 if (theApp.serverconnect->IsLowID())
 statusbar.SetIcon(3,connicons[1]);
 else
 statusbar.SetIcon(3,connicons[2]);
    */
        //statusbar.SetText(GetResString(IDS_MAIN_CONNECTEDTO) +wxString(server),0,0);
        wxStaticText * tx = (wxStaticText *) FindWindow("infoLabel");
        tx->SetLabel(GetResString(IDS_MAIN_CONNECTEDTO) + wxString(server));
        ((wxStaticText *) FindWindow("connLabel"))->SetLabel(server);
        Layout();
        //statusbar.SetTipText(3,server);
        //statusbar.SetText(server,3,0);
    }
    else
    {
        wxStaticBitmap * bmp = (wxStaticBitmap *) FindWindowByName("connImage");
        if (theApp.serverconnect->IsConnecting())
        {
            if (__oldstatus != STAT_CONNECTING)
            {
                bmp->SetBitmap(connImages(0));
                //butn->SetLabel(GetResString(IDS_MAIN_BTN_CANCEL));
                //butn->SetDefaultBitmap(connButImg(2));
                // once again.. no modify
                m_wndToolbar->DeleteTool(ID_BUTTONCONNECT);
                m_wndToolbar->InsertTool(0, ID_BUTTONCONNECT, GetResString(IDS_MAIN_BTN_CANCEL), connButImg(2),
                GetResString(IDS_MAIN_BTN_CANCEL_TOOLTIP));
                m_wndToolbar->Realize();
                __oldstatus = STAT_CONNECTING;
            }
 /*this->GetDlgItem(IDC_BUTTON2)->SetWindowText(GetResString(IDS_MAIN_BTN_CANCEL));
 m_btnConnect.SetIcon(IDI_BN_STOPCONNECTING); m_btnConnect.SetTooltipText(GetResString(IDS_MAIN_BTN_CANCEL_TOOLTIP));
    statusbar.SetIcon(3,connicons[0]);*/
            // EI INFOLABEL
            ((wxStaticText *) FindWindowByName("connLabel"))->SetLabel(GetResString(IDS_CONNECTING));
            Layout();
            //statusbar.SetText(GetResString(IDS_CONNECTING),3,0);
            //statusbar.SetTipText(3,"");
            ShowUserCount(0, 0);
        }
        else
        {
            if (__oldstatus != STAT_NOTCONNECTED)
            {
                bmp->SetBitmap(connImages(0));
                ((wxStaticText *) FindWindowByName("connLabel"))->SetLabel(GetResString(IDS_NOTCONNECTED));
                Layout();
                //butn->SetLabel(GetResString(IDS_MAIN_BTN_CONNECT));
                //butn->SetDefaultBitmap(connButImg(0));
                // and again...
                m_wndToolbar->DeleteTool(ID_BUTTONCONNECT);
                m_wndToolbar->InsertTool(0, ID_BUTTONCONNECT, GetResString(IDS_MAIN_BTN_CONNECT), connButImg(0),
                GetResString(IDS_CONNECTTOANYSERVER));
                m_wndToolbar->Realize();
                __oldstatus = STAT_NOTCONNECTED;
            }
 /*
 this->GetDlgItem(IDC_BUTTON2)->SetWindowText(GetResString(IDS_MAIN_BTN_CONNECT));
 m_btnConnect.SetIcon(IDI_BN_CONNECT);	m_btnConnect.SetTooltipText(GetResString(IDS_CONNECTTOANYSERVER));
 statusbar.SetIcon(3,connicons[0]);
 statusbar.SetText(GetResString(IDS_NOTCONNECTED),3,0);
    */
            ((wxStaticText *) FindWindow("connLabel"))->SetLabel(GetResString(IDS_NOTCONNECTED));
            Layout();
            AddLogLine(true, GetResString(IDS_DISCONNECTED));
            //statusbar.SetTipText(3,"");
            ShowUserCount(0, 0);
        }
    }
}

void CxmuleDlg::ShowUserCount(uint32_t user_toshow, uint32_t file_toshow)
{
    uint32_t totaluser, totalfile;
    totaluser = totalfile = 0;
    if (user_toshow || file_toshow)
    theApp.serverlist->GetUserFileStatus(totaluser, totalfile);
    char buffer[100];
    sprintf(buffer, "%s: %s(%s) | %s: %s(%s)", GetResString(IDS_UUSERS) .GetData(), CastItoIShort(user_toshow) .GetData(), CastItoIShort(totaluser) .GetData(), GetResString(IDS_FILES) .GetData(), CastItoIShort(file_toshow) .GetData(), CastItoIShort(totalfile) .GetData());
    wxStaticCast(FindWindow("userLabel"), wxStaticText)->SetLabel(buffer);
    Layout();
    //statusbar.SetText(buffer,1,0);
}

void CxmuleDlg::ShowMessageState(uint8_t iconnr)
{
    //statusbar.SetIcon(4,imicons[iconnr]);
}

void CxmuleDlg::ShowTransferRate(bool foreceAll)
{
    char buffer[50];
    char buffer2[100];
    wxString ConnState;
    CServer *server;

    lastuprate = theApp.uploadqueue->GetDatarate();
    lastdownrate = theApp.downloadqueue->GetDatarate();
    
    int lastuprateoverhead = theApp.uploadqueue->GetUpDatarateOverhead();
    int lastdownrateoverhead = theApp.downloadqueue->GetDownDatarateOverhead();

    if (theApp.dynprefs->Get<bool>("show-overhead"))
    {
        sprintf(buffer, GetResString(IDS_UPDOWN), (float) lastuprate/ 1024, (float) lastuprateoverhead/ 1024, (float) lastdownrate/ 1024, (float) lastdownrateoverhead/ 1024);
    }
    else
    {
        sprintf(buffer, GetResString(IDS_UPDOWNSMALL), (float) lastuprate/ 1024, (float) lastdownrate/ 1024);
    }

    //statusbar.SetStatusText(buffer,2); //,0);
    ((wxStaticText *) FindWindowByName("speedLabel"))->SetLabel(buffer);
    //Layout();
    
    if (theApp.serverconnect->IsConnected())
    {
        sprintf(buffer2, wxString(_("xMule (%s | ") + GetResString(IDS_CONNECTED) + ")") .GetData(), buffer);
        server = theApp.serverconnect->GetCurrentServer ();
    
        if (server)
        {
            ConnState = GetResString(IDS_CONNECTED) + wxString (" ") + server->GetListName();
        }
    }
    else
    {
        sprintf(buffer2, wxString(_("xMule (%s | ") + GetResString(IDS_DISCONNECTED) + ")") .GetData(), buffer);
        ConnState = GetResString(IDS_DISCONNECTED);
    }

    if (theApp.dynprefs->Get<bool>("daemon") == false)
    {
        // set trayicon-icon
        int DownRateProcent = (int)ceil((lastdownrate / 10.24) / theApp.dynprefs->Get<long>("capacities-download"));
        if (DownRateProcent > 100) DownRateProcent = 100;
        UpdateTrayIcon(DownRateProcent);

        m_wndTaskbarNotifier->TraySetToolTip(buffer2);
    }

    wxStaticBitmap* bmp = (wxStaticBitmap *)FindWindowByName("transferImg");
    
    if (lastuprate && lastdownrate)
    {
        bmp->SetBitmap(transicons[3]);
    }
    else if (lastuprate)
    {
        bmp->SetBitmap(transicons[2]);
    }
    else if (lastdownrate)
    {
        bmp->SetBitmap(transicons[1]);
    }
    else
    {
        bmp->SetBitmap(transicons[0]);
    }

    //PLK Show-Rates on title
    if (theApp.dynprefs->Get<bool>("xfer-on-title") == true)
    {
        if (theApp.dynprefs->Get<bool>("command-line") == true)
        {
            theApp.lda->Print(wxString::Format(wxT("%s v%s --- %s --- %s"), wxT(PACKAGE_NAME), wxT(PACKAGE_VERSION), buffer,ConnState.GetData()),LD_STATUS,true);
        }

        if (theApp.dynprefs->Get<bool>("daemon") == false)
        {
            theApp.xmuledlg->SetTitle(wxString::Format(wxT("%s v%s --- %s"), wxT(PACKAGE_NAME), wxT(PACKAGE_VERSION), buffer));
        }
    }
    else
    {
        if (theApp.dynprefs->Get<bool>("command-line") == true)
        {
            theApp.lda->Print(wxString::Format(wxT("%s v%s --- %s"), wxT(PACKAGE_NAME), wxT(PACKAGE_VERSION),ConnState.GetData()),LD_STATUS,true);
        }
        
        if (theApp.dynprefs->Get<bool>("daemon") == false)
        {
              theApp.xmuledlg->SetTitle(wxString::Format(wxT("%s v%s"), wxT(PACKAGE_NAME), wxT(PACKAGE_VERSION)));
        }
    }
}

void CxmuleDlg::SetActiveDialog(wxWindow * dlg)
{
    activewnd->Show(FALSE);
    contentSizer->Remove(activewnd);
    contentSizer->Add(dlg, 1, wxALIGN_LEFT | wxEXPAND | wxALL, 5);
    dlg->Show(TRUE);
    activewnd = dlg;
    Layout();
}

extern void URLDecode(wxString & result, const char * buff);

void CxmuleDlg::OnHashingShutdown(wxCommandEvent &)
{
    if (m_app_state != APP_STATE_SHUTINGDOWN)
    {
        CAddFileThread::Setup();
    }
    else
    {
        Destroy();
    }
}

void CxmuleDlg::OnClose(wxCloseEvent & evt)
{
    if (evt.CanVeto() && theApp.dynprefs->Get<bool>("prompt-on-exit") == true)
    if (wxNO == wxMessageBox(GetResString(IDS_MAIN_EXIT), GetResString(IDS_MAIN_EXITTITLE), wxYES_NO))
    {
        evt.Veto();
        return;
    }
    // we are going DOWN
    m_app_state = APP_STATE_SHUTINGDOWN;
    // Added By Bouc7:
    theApp.OnlineSig();
    // Close sockets to avoid new clients coming in
    theApp.listensocket->StopListening();
    NewSocket_Stop(1);
    theApp.serverconnect->Disconnect();
    // Signal the hashing thread to terminate
    CAddFileThread::Shutdown();
    // TODO: Add your message handler code here and/or call default
    //WINDOWPLACEMENT wp;wp.length=sizeof(wp);GetWindowPlacement(&wp);
    //theApp.glob_prefs->SetWindowLayout(wp);
    // saving data & stuff
    theApp.knownfiles->Save();
    transferwnd->downloadlistctrl->SaveSettings(CPreferences::tableDownload);
    transferwnd->uploadlistctrl->SaveSettings(CPreferences::tableUpload);
    transferwnd->queuelistctrl->SaveSettings(CPreferences::tableQueue);
    sharedfileswnd->sharedfilesctrl->SaveSettings(CPreferences::tableShared);
    serverwnd->serverlistctrl->SaveSettings(CPreferences::tableServer);
    theApp.glob_prefs->Add2TotalDownloaded(theApp.stat_sessionReceivedBytes);
    theApp.glob_prefs->Add2TotalUploaded(theApp.stat_sessionSentBytes);
    // Save friends
    theApp.friendlist->SaveList();
    // Save Preferences && Shared Dirs
    if (theApp.glob_prefs->Save(5))
    {
#if defined(__DEBUG__)
        printf("xmuleDlg: Save() returned 1\n");
#endif
        ;
    }
    transferwnd->downloadlistctrl->DeleteAllItems();
    //xmuledlg->chatwnd->chatselector->DeleteAllItems();
    theApp.clientlist->DeleteAll();
    // Hint: Destroying the window is delayed until the hashing thread
    //       does signal its termination.
    //  Destroy();
    //CTrayDialog::OnCancel();
}

void CxmuleDlg::StartConnection()
{
    AddLogLine(true, GetResString(IDS_CONNECTING));
    theApp.serverconnect->ConnectToAnyServer();
    ShowConnectionState(false);
}

void CxmuleDlg::CloseConnection()
{
    theApp.serverconnect->Disconnect();
    // Added By Bouc7:
    theApp.OnlineSig();
}

void CxmuleDlg::RestoreWindow()
{
    //if (TrayIsVisible()) TrayHide();
    //ShowWindow(SW_SHOW);
}

void CxmuleDlg::ShowStatistics()
{
    statisticswnd->ShowStatistics();
}

void CxmuleDlg::UpdateTrayIcon(int procent)
{
    //HICON mytrayIcon;
    //if (mytrayIcon!=NULL) DestroyIcon(mytrayIcon);
    // set the limits of where the bar color changes (low-high)
    int pLimits16[1] =
    {
        100
        };
    // set the corresponding color for each level
    COLORREF pColors16[1] =
    {
        theApp.glob_prefs->GetStatsColor(11)
        };
    // load our limit and color info
    m_wndTaskbarNotifier->SetColorLevels(pLimits16, pColors16, 1);
    // generate the icon (destroy these icon using DestroyIcon())
    int pVals16[1] =
    {
        procent
        };
    // ei hienostelua. tarvii kuitenki pelleillä gtk:n kanssa
    char ** data;
    if (!theApp.serverconnect)
    data = mule_Tr_grey_ico;
    else
    {
        if (theApp.serverconnect->IsConnected())
        if (!theApp.serverconnect->IsLowID())
        {
            data = mule_TrayIcon_ico;
        }
        else
        {
            data = mule_Tr_yellow_ico;
        }
        else data = mule_Tr_grey_ico;
    }
    m_wndTaskbarNotifier->TraySetIcon(data, true, pVals16);
}

//START - enkeyDEV(kei-kun) -TaskbarNotifier-
void CxmuleDlg::ShowNotifier(wxString Text, int MsgType, bool ForceSoundOFF)
{
}

//END - enkeyDEV(kei-kun) -TaskbarNotifier-

void CxmuleDlg::Localize()
{
}

void CxmuleDlg::OnUDPTimer(wxTimerEvent & evt)
{
    if (!IsRunning())
    return;
    theApp.serverlist->SendNextPacket();
}

void CxmuleDlg::OnSocketTimer(wxTimerEvent & evt)
{
    if (!IsRunning())
    return;
    CServerConnect * _this = theApp.serverconnect;
    _this->StopConnectionTry();
    if (_this->IsConnected()) return;
    _this->ConnectToAnyServer();
}

void CxmuleDlg::OnQLTimer(wxTimerEvent & evt)
{
    if (!IsRunning())
    return;
    CQueueListCtrl::QueueUpdateTimer();
}

void CxmuleDlg::MinimizeDlg(wxIconizeEvent& event)
{
    if ((theApp.dynprefs->Get<bool>("mimimize-to-tray") == true) && (theApp.dynprefs->Get<long>("systray-integration") != 3) && (event.Iconized() == true))
    {
        theApp.xmuledlg->Show(false);
    }
    else
    {
        theApp.xmuledlg->Show(true);
    }
}

