/*
	Rogue Trader.
	Copyright (c) 2007, Darragh Coy.
	All rights reserved.
	Original work(s), source code & author(s) details available at: http://www.darraghcoy.com

	Redistribution and use in source and binary forms, with or without modification, are permitted 
	provided that the following conditions are met:

		* 	Redistributions of source code must retain the above copyright notice, this list of 
			conditions and the following disclaimer.
		* 	Redistributions in binary form must reproduce the above copyright notice, this list of 
			conditions and the following disclaimer in the documentation.
		* 	Neither the name of the author nor the names of contributors may be used to endorse or 
			promote products derived from this software without specific prior written permission.
		* 	The use of any third party libraries, modules or data files provided with the source 
			form of the program must follow and respect the individual licensing terms of these 
			components. You do not have permission to modify or circumvent the licensing terms for 
			provided third party components unless the third party licenses specifically allow this. 
			If you do not agree to the terms of provided third party components then you do not have 
			permission to use them in your derived work(s).
		* 	The terms of this license do not apply to separate (but related) distributions if supplied 
			by the author(s), only to the contents of this source distribution, derived works, and the 
			binaries produced by either modified or unmodified versions of the source code. The terms 
			of this license do not also apply to any third party libraries or components provided with 
			the source distribution. Such third party elements are licensed under their own separate 
			agreements.

	THIS SOFTWARE IS PROVIDED BY DARRAGH COY ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
	ARE DISCLAIMED. IN NO EVENT SHALL DARRAGH COY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
	OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
	OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
	IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################
//
//
// Class Name:   GuiLoadGame
// Purpose:      This widget allows loading / deletetion from one particular file.
//               It also displays information on the save game.
//
//
//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################

#include "GuiLoadGame.h"
#include "SaveDataFolder.h"

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     GuiLoadGame::GuiLoadGame()
Purpose:  Constructor for this widget.
Params:   Pointer to the game. If no pointer is supplied then this widget creates
          a game object itself. Name of save file used by the widget.
Returns:  n/a

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

GuiLoadGame::GuiLoadGame( Game * game , const char * fileName )
{
    // Save the pointer to the game object and file used

    this->game = game;  this->fileName = fileName;

    // Check for existance of the save file:

    checkFile();
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     GuiLoadGame::mouseMoved()
Purpose:  Mouse moved event for this widget.
Params:   mouse position
Returns:  none

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

void GuiLoadGame::mouseMoved( int x , int y )
{
    //--------------------------------------------------------------------------
    // See if the mouse is over the load button:
    //--------------------------------------------------------------------------

    if (
            x >= buttonLoad.getPositionX()
            &&
            y >= buttonLoad.getPositionY()
            &&
            x <  buttonLoad.getPositionX() + buttonLoad.getSizeX()
            &&
            y <  buttonLoad.getPositionY() + buttonLoad.getSizeY()
        )
    {
        // If the button is not in focus then send the gained focus event:

        if ( buttonLoad.getFocus() == false )
        {
            buttonLoad.setFocus(true);
            buttonLoad.gainedFocus(x,y);
        }

        // Send the mouse moved event to the button:

        buttonLoad.mouseMoved(x,y);
    }
    else
    {
        // If the button has focus then make it loose it:

        if ( buttonLoad.getFocus() == true )
        {
            buttonLoad.setFocus(false);
            buttonLoad.lostFocus();
        }
    }

    //--------------------------------------------------------------------------
    // See if the mouse is over the delete button:
    //--------------------------------------------------------------------------

    if (
            x >= buttonDelete.getPositionX()
            &&
            y >= buttonDelete.getPositionY()
            &&
            x <  buttonDelete.getPositionX() + buttonDelete.getSizeX()
            &&
            y <  buttonDelete.getPositionY() + buttonDelete.getSizeY()
        )
    {
        // If the button is not in focus then send the gained focus event:

        if ( buttonDelete.getFocus() == false )
        {
            buttonDelete.setFocus(true);
            buttonDelete.gainedFocus(x,y);
        }

        // Send the mouse moved event to the button:

        buttonDelete.mouseMoved(x,y);
    }
    else
    {
        // If the button has focus then make it loose it:

        if ( buttonDelete.getFocus() == true )
        {
            buttonDelete.setFocus(false);
            buttonDelete.lostFocus();
        }
    }
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     GuiLoadGame::mousePressed()
Purpose:  Mouse pressed event for the widget:
Params:   none
Returns:  none

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

void GuiLoadGame::mousePressed( int x , int y , GLWindow::MouseButton button )
{
    // See if the mouse is over the load button:

    if (
            x >= buttonLoad.getPositionX()
            &&
            y >= buttonLoad.getPositionY()
            &&
            x <  buttonLoad.getPositionX() + buttonLoad.getSizeX()
            &&
            y <  buttonLoad.getPositionY() + buttonLoad.getSizeY()
        )
    {
        // Send the mouse pressed event to the load button:

        buttonLoad.mousePressed(x,y,button);
    }

    // See if the mouse is over the delete button:

    if (
            x >= buttonDelete.getPositionX()
            &&
            y >= buttonDelete.getPositionY()
            &&
            x <  buttonDelete.getPositionX() + buttonDelete.getSizeX()
            &&
            y <  buttonDelete.getPositionY() + buttonDelete.getSizeY()
        )
    {
        // Send the mouse pressed event to the delete button:

        buttonDelete.mousePressed(x,y,button);
    }
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     GuiLoadGame::mouseReleased()
Purpose:  Mouse released event for the widget:
Params:   none
Returns:  none

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

void GuiLoadGame::mouseReleased( int x , int y , GLWindow::MouseButton button )
{
    // See if the mouse is over the load button:

    if (
            x >= buttonLoad.getPositionX()
            &&
            y >= buttonLoad.getPositionY()
            &&
            x <  buttonLoad.getPositionX() + buttonLoad.getSizeX()
            &&
            y <  buttonLoad.getPositionY() + buttonLoad.getSizeY()
        )
    {
        // If the button is depressed then load the game in this slot:

        if ( buttonLoad.isDepressed() )
        {
            // If the file doesn't exist then warn the user:

            if ( fileExists )
            {
                // If the game doesn't exist then create it: otherwise load

                if ( game == 0  )
                {
                    // Draw a loading screen

                    Game::drawLoadingScreen();

                    // Create the game:

                    Game * game = new Game(""); game->pause();

                    // Load the saved game:

                    SaveGame::load(game,fileName.c_str());

                    // Run the game from here: but only if load was successful and players name is not empty:

                    if ( game->getPlayer()->getName()[0] != 0 )
                    {
                        // Load successful: run the game

                        game->unpause(); game->run();
                    }

                    // Delete the game when done:

                    delete game;
                }
                else
                {
                    // Game already exists: draw a loading screen

                    Game::drawLoadingScreen();

                    // Load thte game:

                    SaveGame::load(game,fileName.c_str());
                }
            }
            else
            {
                // No file to load: warn user

                GuiScreen::showMessageDialog("Load Game","No game exists in this slot to load.");
            }
        }

        // Send the mouse released event to the load button:

        buttonLoad.mouseReleased(x,y,button);
    }

    // See if the mouse is over the delete button:

    if (
            x >= buttonDelete.getPositionX()
            &&
            y >= buttonDelete.getPositionY()
            &&
            x <  buttonDelete.getPositionX() + buttonDelete.getSizeX()
            &&
            y <  buttonDelete.getPositionY() + buttonDelete.getSizeY()
        )
    {
        // If the button is depressed then delete the game in this slot:

        if ( buttonDelete.isDepressed() )
        {
            // If the file doesn't exist then warn the user:

            if ( fileExists )
            {
                // File exists: Confirm with the user first:

                if ( GuiScreen::showQuestionDialog("Delete Game","You have chosen to delete this game.","Are you sure you want to delete ?") )
                {
                    // Deletion confirmed: delete the game

                    deleteFile();
                }
            }
            else
            {
                // No file to delete: warn user

                GuiScreen::showMessageDialog("Delete Game","No game exists in this slot to delete.");
            }
        }

        // Send the mouse released event to the delete button:

        buttonDelete.mouseReleased(x,y,button);
    }
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     GuiLoadGame::lostFocus()
Purpose:  Lost focus event for the widget:
Params:   none
Returns:  none

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

void GuiLoadGame::lostFocus()
{
    // If either of the two buttons are in focus then make them loose focus:

    if ( buttonLoad.getFocus() )
    {
        buttonLoad.setFocus(false); buttonLoad.lostFocus();
    }

    if ( buttonDelete.getFocus() )
    {
        buttonDelete.setFocus(false); buttonDelete.lostFocus();
    }
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     GuiLoadGame::windowRedrawing()
Purpose:  Redraw event for this widget. Draws the widget.
Params:   none
Returns:  none

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

void GuiLoadGame::windowRedrawing()
{
    //--------------------------------------------------------------------------
    // Check for existance of the save file:
    //--------------------------------------------------------------------------

    checkFile();

    //--------------------------------------------------------------------------
    // Draw the main panel
    //--------------------------------------------------------------------------

    mainPanel.setSize       ( size_x        , size_y     );
    mainPanel.setPosition   ( position_x    , position_y );
    mainPanel.setRaised     ( false );

    mainPanel.windowRedrawing();

    //--------------------------------------------------------------------------
    // Draw the load and delete buttons
    //--------------------------------------------------------------------------

    buttonLoad.setSize          ( 128, 32 );
    buttonLoad.setPosition      ( position_x + size_x - 130 , position_y + 4 );
    buttonLoad.setLabel         ( "Load"  );

    buttonLoad.windowRedrawing();

    buttonDelete.setSize        ( 128, 32 );
    buttonDelete.setPosition    ( position_x + size_x - 130 , position_y + 40 );
    buttonDelete.setLabel       ( "Delete"  );

    buttonDelete.windowRedrawing();

    //--------------------------------------------------------------------------
    // If the file exists then draw the date and time of the file:
    //--------------------------------------------------------------------------

    if ( fileExists )
    {
        // Get the main font from the game:

        GLFont * font = GLFontManager::getFont_main();

        // Print the date and time to a buffer:

        char buffer[256];

        sprintf_s
        (
            buffer					,
            256						,
            "%1s %2s %3s %4s %5s"	,
            fileDay					,
            fileMonthDay			,
            fileMonth				,
            fileYear				,
            fileTime
        );

        // Show this to the screen:

        font->drawString
        (
            buffer										,
            float( mainPanel.getPositionX() + 16	)	,
            float( mainPanel.getPositionY() + 16	)	,
            8.0f	,
            0.0f	,
            0.0f	,
            0.0f
        );

        // Show the commander name to the screen:

        sprintf_s( buffer , 256 , "Player: %1s" , fileCommander );

        font->drawString
        (
            buffer										,
            float( mainPanel.getPositionX() + 16	)	,
            float( mainPanel.getPositionY() + 40	)	,
            8.0f	,
            0.0f	,
            0.0f	,
            0.0f	
        );

        // Show the system name to the screen:

        sprintf_s( buffer , 256 , "System: %1s" , fileSystem );

        font->drawString
        (
            buffer										,
            float( mainPanel.getPositionX() + 16	)	,
            float( mainPanel.getPositionY() + 56	)	,
            8.0f	,
            0.0f	,
            0.0f	,
            0
        );
    }
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     GuiLoadGame::checkFile()
Purpose:  Checks for the existance of the save file used by this widget.
Params:   none
Returns:  none

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

void GuiLoadGame::checkFile()
{
    // Make sure the save game folder exists:
    
    SaveDataFolder::CreateSaveFolder("Darragh Coy\\Rogue Trader");

    // Search for the file:

    WIN32_FIND_DATA findData;
    HANDLE          fileHandle;

    fileHandle = FindFirstFile( fileName.c_str() , & findData );

    // If the file exists then get the information on it:

    if ( fileHandle != INVALID_HANDLE_VALUE )
    {
        //----------------------------------------------------------------------
        // File exists: get time at which file was last written to:
        //----------------------------------------------------------------------

        // Set the file exists flag to true

        fileExists = true;

        // Convert the last time the file was written to into the system time format

        SYSTEMTIME systemTime;

        FileTimeToSystemTime( &findData.ftLastWriteTime , &systemTime );

        //----------------------------------------------------------------------
        // Convert the system time values into strings:
        //----------------------------------------------------------------------

        // Save year

        sprintf_s(fileYear,8,"%1i", (int)(systemTime.wYear) );

        // Save month:

        switch ( systemTime.wMonth )
        {
            case 0 : sprintf_s(fileMonth,16,"Invalid");      break;
            case 1 : sprintf_s(fileMonth,16,"January");      break;
            case 2 : sprintf_s(fileMonth,16,"February");     break;
            case 3 : sprintf_s(fileMonth,16,"March");        break;
            case 4 : sprintf_s(fileMonth,16,"April");        break;
            case 5 : sprintf_s(fileMonth,16,"May");          break;
            case 6 : sprintf_s(fileMonth,16,"June");         break;
            case 7 : sprintf_s(fileMonth,16,"July");         break;
            case 8 : sprintf_s(fileMonth,16,"August");       break;
            case 9 : sprintf_s(fileMonth,16,"September");    break;
            case 10: sprintf_s(fileMonth,16,"October");      break;
            case 11: sprintf_s(fileMonth,16,"November");     break;
            case 12: sprintf_s(fileMonth,16,"December");     break;
            default: sprintf_s(fileMonth,16,"Invalid");      break;
        }

        // Save day of week:

        switch ( systemTime.wDayOfWeek )
        {
            case 0 : sprintf_s(fileDay,16,"Sunday");     break;
            case 1 : sprintf_s(fileDay,16,"Monday");     break;
            case 2 : sprintf_s(fileDay,16,"Tuesday");    break;
            case 3 : sprintf_s(fileDay,16,"Wednesday");  break;
            case 4 : sprintf_s(fileDay,16,"Thursday");   break;
            case 5 : sprintf_s(fileDay,16,"Friday");     break;
            case 6 : sprintf_s(fileDay,16,"Saturday");   break;
            default: sprintf_s(fileDay,16,"Invalid");    break;
        }

        // Save day of month:

        sprintf_s( fileMonthDay , 8 , "%1i" , (int)(systemTime.wDay) );

        // Append a postfix to the day of the month:

        if ( systemTime.wDay < 10 || systemTime.wDay > 19 )
        {
            if ( systemTime.wDay % 10 == 1 )
            {
                strcat_s( fileMonthDay , 8 , "st" );
            }
            else if ( systemTime.wDay % 10 == 2 )
            {
                strcat_s( fileMonthDay , 8 , "nd" );
            }
            else if ( systemTime.wDay % 10 == 3 )
            {
                strcat_s( fileMonthDay , 8 , "rd" );
            }
            else
            {
                strcat_s( fileMonthDay , 8 , "th" );
            }
        }
        else
        {
            strcat_s( fileMonthDay , 8 , "th" );
        }

        // Save hour and minute:

        sprintf_s( fileTime , 16 , "%001i:%002i" , (int)(systemTime.wHour) , (int)(systemTime.wMinute) );

        // Close up the file after done:

        FindClose(fileHandle);

        //----------------------------------------------------------------------
        // Try and read the system and commander name from the file:
        //----------------------------------------------------------------------

        // Set the commander and system name to null initially:

        memset( fileSystem    , 0 , 256 );
        memset( fileCommander , 0 , 256 );

        // Open the save file:

        FILE * file = 0; fopen_s( &file , fileName.c_str() , "rb" );

        if ( file )
        {
            //------------------------------------------------------------------
            // Try to read the name from the file:
            //------------------------------------------------------------------

            // Ignore the first 16 bytes: these are the file ids

            fseek( file , 16 , SEEK_CUR );

            // Read the system name: 255 bytes in total

            fread( fileSystem , 1 , 255 , file );

            // Read the commander name: 255 bytes in total

            fread( fileCommander , 1 , 255 , file );

            // Close the file:

            fclose(file);
        }
        else
        {
            //------------------------------------------------------------------
            // Couldn't read the file. set file exists to false:
            //------------------------------------------------------------------

            fileExists = false;
        }
    }
    else
    {
        //----------------------------------------------------------------------
        // File does not exist:
        //----------------------------------------------------------------------

        fileExists = false;
    }
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     GuiLoadGame::deleteFile()
Purpose:  Deletes the save file used by this widget.
Params:   none
Returns:  none

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

void GuiLoadGame::deleteFile()
{
    // Try to delete the save file:

    DeleteFile( fileName.c_str() );
}
