/*
 * pawsserverlist.cpp - Author: Christian Svensson
 *
 * Copyright (C) 2004 Atomic Blue (info@planeshift.it, http://www.atomicblue.org)
 *
 *
 * 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 (version 2 of the License)
 * 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

#include <psconfig.h>
#include "updaterglobals.h"

#include <csutil/cfgfile.h>
#include <iutil/databuff.h>
#include <iengine/engine.h>

// PAWS INCLUDES
#include "pawsserverlist.h"
#include "paws/pawsmanager.h"
#include "paws/pawslistbox.h"
#include "paws/pawsbutton.h"

#include "net/serverpinger.h"

#define SERVER_LIST_FILE     "/planeshift/data/servers.xml"

pawsServerList::pawsServerList()
{
    servers = NULL;
    btnPing = NULL;
    btnCancel = NULL;
    server = NULL;
}

bool pawsServerList::PostSetup()
{
    servers = (pawsListBox*)FindWidget("servers");
    if(!servers)
        return false;

    btnPing = (pawsButton*)FindWidget("PingButton");
    if(!btnPing)
        return false;

    btnCancel = (pawsButton*)FindWidget("CancelButton");
    if(!btnCancel)
        return false;

    // Add the servers
    csRef<iDocumentSystem> xml = psupdaterengine->GetDocumentSystem();
    csRef<iVFS> vfs = psupdaterengine->GetVFS();
    
    csRef<iDataBuffer> buff = vfs->ReadFile( SERVER_LIST_FILE );

    if ( !buff || !buff->GetSize() )
    {
        Error2("File %s not found!", SERVER_LIST_FILE);
        return false;
    }
    
    csRef<iDocument> doc = xml->CreateDocument();
    const char* error = doc->Parse( buff );
    if ( error )
    {
        Error2("ERROR: %s", error );
        return false;
    }

    csRef<iDocumentNode> root = doc->GetRoot();
    if(!root)
    {
        Error2("No XML root in %s", SERVER_LIST_FILE);
        return false;
    }
    
    csRef<iDocumentNode> topNode = root->GetNode("serverlist");
    if (!topNode)
    {
        Error2("No <serverlist> tag in %s", SERVER_LIST_FILE);
        return false;
    }
    csRef<iDocumentNodeIterator> iter = topNode->GetNodes();
    
    while ( iter->HasNext() )
    {
        csRef<iDocumentNode> node = iter->Next();

        if(node->GetType() == CS_NODE_COMMENT)
            continue;

        csString port;
        csRef<iDocumentAttribute> portAttr = node->GetAttribute("port");
        if (portAttr != NULL)
            port = portAttr->GetValue();
        else
            port = "13331";

        pawsListBoxRow* row = servers->NewRow();

        pawsTextBox* name = (pawsTextBox*)row->GetColumn(0);
        pawsTextBox* ip = (pawsTextBox*)row->GetColumn(1);
        pawsTextBox* portT = (pawsTextBox*)row->GetColumn(2);

        name->SetText(node->GetAttributeValue("name"));
        ip->SetText(node->GetAttributeValue("ip"));
        portT->SetText(port);
    }

    this->Show();
    return true;
}

bool pawsServerList::OnButtonPressed(int button, int keyModifier, pawsWidget* widget)
{
    pawsButton* btnPressed = (pawsButton*)widget;

    if(btnPressed == btnPing)
    {
        // Lets ping then
        if(server)
        {
            server->Disconnect();
            delete server;
            server = NULL;
        }

        pawsListBoxRow* row = servers->GetSelectedRow();
        pawsTextBox* name = (pawsTextBox*)row->GetColumn(0);
        pawsTextBox* ip = (pawsTextBox*)row->GetColumn(1);
        pawsTextBox* port = (pawsTextBox*)row->GetColumn(2);

        int nport = atoi(port->GetText());

        server = new psServerPinger(
            name->GetText(),
            ip->GetText(),
            nport,
            psupdaterengine->GetObjectRegistry());
        server->Connect();
        btnCancel->Hide();
    }

    if(btnPressed == btnCancel)
    {
        this->SetAlwaysOnTop(false);
        this->Hide();
    }

    return true;
}

void pawsServerList::Draw()
{
    if(server)
    {
        server->DoYourWork();
        if (server->GetPing() != -1)
        {
            if(server->GetPing() != 9999)
            {
                csString pingStr;
                pingStr.Format("Game server %s responded after %d ms",server->GetName().GetData(),server->GetPing());
                PawsManager::GetSingleton().CreateWarningBox(pingStr);
                server->Disconnect();
                delete server;
                server = NULL;
                btnCancel->Show();
            }
        }
        else
        {
            PawsManager::GetSingleton().CreateWarningBox("Server didn't respond");
            server->Disconnect();
            delete server;
            server = NULL;
            btnCancel->Show();
        }
    }

    pawsWidget::Draw();
}

void pawsServerList::SelectFirstServer()
{
    if (servers->GetRowCount()!=0)
        servers->Select(servers->GetRow(0));
}

