/*
 * pawsupdaterwindow.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 "changelist.h"

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

// PAWS INCLUDES
#include "pawsupdaterwindow.h"
#include "paws/pawsmanager.h"
#include "paws/pawsradio.h"
#include "paws/pawscheckbox.h"
#include "paws/pawstextbox.h"
#include "paws/pawsprogressbar.h"
#include "pawsserverlist.h"
#include "pawsupdateroptions.h"

using updater::ChangeList;

pawsUpdaterWindow::pawsUpdaterWindow()
{
    maxSize = 0;
    prevSize = 0;
}

bool pawsUpdaterWindow::PostSetup()
{
 
    btnUpdate     = (pawsButton*)FindWidget("UpdateButton");
    if (!btnUpdate)
        return false;

    btnExit       = (pawsButton*)FindWidget("ExitButton");
    if (!btnExit)
        return false;

    btnOptions      = (pawsButton*)FindWidget("OptionsButton");
    if (!btnOptions)
        return false;

    btnCheck      = (pawsButton*)FindWidget("CheckButton");
    if (!btnCheck)
        return false;

    prgBar        = (pawsProgressBar*)FindWidget("UpdateProgress");
    if (!prgBar)
        return false;

    prgTotal        = (pawsProgressBar*)FindWidget("TotalProgress");
    if (!prgTotal)
        return false;

    txtFile       = (pawsTextBox*)FindWidget("file");
    if (!txtFile)
        return false;

    lblUpdate       = (pawsTextBox*)FindWidget("UpdateLbl");
    if (!lblUpdate)
        return false;

    lblTotal       = (pawsTextBox*)FindWidget("TotalLbl");
    if (!lblTotal)
        return false;

    lblSpeed       = (pawsTextBox*)FindWidget("SpeedLbl");
    btnLaunch      = (pawsButton*)FindWidget("GameButton");
    // No check because not critical

    prgBar->SetTotalValue(101); //101 looks nicer
    prgBar->SetCurrentValue(0);

    prgTotal->SetTotalValue(101); //101 looks nicer
    prgTotal->SetCurrentValue(0);

    pawsMessageTextBox* msgBox = (pawsMessageTextBox*)FindWidget("list");

    csString ver,str;
    ver = UPDATER_VERSION;
    for(size_t i = 1;i < ver.Length();i++)
    {
        ver.Insert(i,'.');
        i++; // Jump twice
    }
    str.Format("Welcome to the PlaneShift updater version %s!",ver.GetData());

    msgBox->AddMessage(str,graphics2D->FindRGB(255,255,255));
    msgBox->AddMessage("Click Update to start");
    return true;
}

bool pawsUpdaterWindow::OnButtonPressed( int mouseButton, int keyModifier, pawsWidget* widget )
{
    if (widget==btnUpdate)
    {
        if (psupdaterengine->CanUpdate())
            psupdaterengine->GetUpdater()->StartUpdate();
            
        // This is the cancel button when updating
        SetUpdateButtonText("Cancel");
    } 
    else if (widget==btnCheck)
    {
        pawsServerList* list = (pawsServerList*)PawsManager::GetSingleton().FindWidget("serverlist");
        if (list)
        {
            list->Show();
            list->SelectFirstServer();
            list->SetAlwaysOnTop(true);
        }
    }
    else if (widget==btnOptions)
    {
        if (psupdaterengine->GetUpdater()->IsRunning())
        {
            PawsManager::GetSingleton().CreateWarningBox("You can't change the options while you are updating");
            return true;
        }

        pawsUpdaterOptions* opts = (pawsUpdaterOptions*)PawsManager::GetSingleton().FindWidget("options");
        if (opts)
        {
            opts->Show();
            opts->SetAlwaysOnTop(true);
        }
    }
    else if (widget==btnExit)
    {
        psupdaterengine->QuitClient();
    }
    else if (widget==btnLaunch)
    {
        if (psupdaterengine->GetUpdater()->IsRunning())
        {
            PawsManager::GetSingleton().CreateWarningBox("You can't launch PlaneShift while you are updating");
            return true;
        }

        // Begin OS specific execution
#ifdef CS_PLATFORM_WIN32
        // Lanuch PlaneShift in the win way
        STARTUPINFO si;
        PROCESS_INFORMATION pi;

        ZeroMemory( &si, sizeof(si) );
        si.cb = sizeof(si);
        ZeroMemory( &pi, sizeof(pi) );

        // Start the second updater process. 
        CreateProcess( NULL,    // No module name (use command line). 
            "psclient.exe",     // Command line.
            NULL,               // Process handle not inheritable. 
            NULL,               // Thread handle not inheritable. 
            FALSE,              // Set handle inheritance to FALSE. 
            CREATE_NEW_CONSOLE, // Give the process it's own console
            NULL,               // Use parent's environment block. 
            NULL,               // Use parent's starting directory. 
            &si,                // Pointer to STARTUPINFO structure.
            &pi );              // Pointer to PROCESS_INFORMATION structure.

#elif defined(CS_PLATFORM_UNIX)
        // *NIX have a quite easier way to do that :)
        system("./psclient &");
#else
#error "Bad platform for launch"
#endif
        psupdaterengine->QuitClient();
    }

    return false;
}

void pawsUpdaterWindow::SetTotalSize(float value)
{
    maxSize = value;
    prevSize = 0;
}

void pawsUpdaterWindow::SetSpeed(double speed)
{
    if(!lblSpeed)
        return;

    csString txt;
    txt.Format("%.1f KB/s",(float)speed);
    lblSpeed->SetText(txt);
}

void pawsUpdaterWindow::UpdateFileSize(const char* name,float size)
{
    txtFile->SetText(name);
    SetProgressValue(0);

    if (prevSize != 0 )
    {
        float totalprg = float(prevSize)/(float)maxSize;
        SetTotalProgressValue((int)(totalprg*100));
    }

    prevSize += size;
    return;
}

void pawsUpdaterWindow::SetProgressValue(int value)
{
    if (value > 100)
    {
        csString text;
        text = "100%";
        lblUpdate->SetText(text);
    }
    else
    {
        csString text;
        text = value;
        text += "%";
        lblUpdate->SetText(text);
    }

    prgBar->SetCurrentValue(value);
}


void pawsUpdaterWindow::SetTotalProgressValue(int value)
{
    if (value > 100)
    {
        csString text;
        text = "100%";
        lblTotal->SetText(text);
    }
    else
    {
        csString text;
        text = value;
        text += "%";
        lblTotal->SetText(text);
    }

    prgTotal->SetCurrentValue(value);
}

void pawsUpdaterWindow::SetExit(bool v)
{
    if(v)
        btnExit->Show();
    else
        btnExit->Hide();
}

void pawsUpdaterWindow::SetUpdateButtonText(const char* text)
{
    btnUpdate->SetText(text);
}
