/*
	Trampoline Sim.
	Copyright (c) 2009, 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.
*/

//=====================================================================================================================
/// @brief		Class representing commonly used dialog boxes. Functions for showing those boxes and getting input 
///				from the boxes.
//=====================================================================================================================

#include "Precompiled.h"
#include "Windows\Dialogs.h"
#include "Windows\Window.h"

using namespace Game;

//=====================================================================================================================
/// @brief		Shows a yes/no question box
/// @param		window - owner window of the dialog. if null then dialog is not blocking.
/// @param		question - question to ask
/// @param		title - title of the dialog box
/// @returns	true if the user clicked yes, false otherwise
//=====================================================================================================================

bool Dialogs::ShowQuestionBox( Window * window, std::string question, std::string title )
{
	// Get window handle:

	HWND handle = 0; if ( window != 0 ) handle = window->GetWindowHandle();

    // Show the message box

    int answer = MessageBoxA
    (
       handle,
	   question.c_str(),
	   title.c_str(),
       MB_YESNO | MB_ICONQUESTION | MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND
	);

    // Return answer

    if ( answer == IDYES ) return true; else return false;
}

//=====================================================================================================================
/// @brief	Shows a message box with specified text and title
/// @param	window - owner window of the dialog. if null then dialog is not blocking.
/// @param	message - message to show
/// @param	title - title of the dialog box
//=====================================================================================================================

void Dialogs::ShowMessageBox( Window * window, std::string message, std::string title )
{
	// Get window handle:

	HWND handle = 0; if ( window != 0 ) handle = window->GetWindowHandle();

    // Show the message box

    MessageBoxA
    (
        handle,
        message.c_str(),
        title.c_str(),
        MB_OK | MB_ICONINFORMATION | MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND
    );
}

//=====================================================================================================================
/// @brief		Shows an file open dialog.
/// @param		window - owner window of the dialog. if null then dialog is not blocking.
/// @returns	name of file user wants to open or a zero length string if none was selected
//=====================================================================================================================

std::string Dialogs::ShowOpenFileBox( Window * window )
{
	// Get window handle:

	HWND handle = 0; if ( window != 0 ) handle = window->GetWindowHandle();

    // Declare an open file name structure:

	OPENFILENAMEA ofn = {0};

    // Store the chosen file name here:

    static char name[MAX_PATH+1]; name[0] = 0;

    // Fill in the required fields:

    ofn.lStructSize = sizeof(OPENFILENAMEA);    // fill in structure size
    ofn.hwndOwner   = handle;					// window that owns the dialog
    ofn.lpstrFile   = name;						// buffer to dump file name into
    ofn.nMaxFile    = MAX_PATH;					// Maxmimum file name lenght
    ofn.Flags      |= OFN_CREATEPROMPT;         // Prompt user to create file if not existing
    ofn.Flags      |= OFN_LONGNAMES;            // Use long name format not 8.3
    ofn.Flags      |= OFN_NOCHANGEDIR;          // Don't allow working dir to be changed
    ofn.Flags      |= OFN_FILEMUSTEXIST;        // File must exist

    // Try and open a file:

    if ( GetOpenFileNameA(&ofn) != 0 )
    {
        // File choosen: return the file choosen:

        return std::string(name);
    }
    else
    {
        // No file chosen: return a blank string

        return std::string("");
    }
}

//=====================================================================================================================
/// @brief		Shows an file save dialog.
/// @param		window - owner window of the dialog. if null then dialog is not blocking.
/// @returns	name of file user wants to save to or a zero length string if none was selected
//=====================================================================================================================

std::string Dialogs::ShowSaveFileBox( Window * window )
{
	// Get window handle:

	HWND handle = 0; if ( window != 0 ) handle = window->GetWindowHandle();

    // Declare an open file name structure:

    OPENFILENAMEA ofn = { 0 };

    // Store the chosen file name here:

    static char name[MAX_PATH+1]; name[0] = 0;

    // Fill in the required fields:

    ofn.lStructSize = sizeof(OPENFILENAMEA);    // fill in structure size
    ofn.hwndOwner   = handle;					// window that owns the dialog
    ofn.lpstrFile   = name;						// buffer to dump file name into
    ofn.nMaxFile    = MAX_PATH;					// Maxmimum file name lenght
    ofn.Flags      |= OFN_CREATEPROMPT;         // Prompt user to create file if not existing
    ofn.Flags      |= OFN_LONGNAMES;            // Use long name format not 8.3
    ofn.Flags      |= OFN_OVERWRITEPROMPT;      // Create an overwrite prompt
    ofn.Flags      |= OFN_NOCHANGEDIR;          // Don't allow working dir to be changed

    // Try and choose a file:

    if ( GetSaveFileNameA( &ofn ) )
    {
        // File choosen: return the file choosen:

        return std::string(name);
    }
    else
    {
        // No file chosen: return a blank string

        return std::string("");
    }
}

//=====================================================================================================================
/// @brief		Shows a file open dialog.
/// @param		window - owner window of the dialog. if null then dialog is not blocking.
/// @param		title - title for the dialog box
/// @param		start_dir - directory to start in
/// @param		types_and_filters - list containing pairs of file type names and filters
/// @returns	name of file user wants to open or a zero length string if none was selected
//=====================================================================================================================

std::string Dialogs::ShowOpenFileBox
( 
	Window * window , 
	std::string title , 
	std::string start_dir , 
	std::list< std::pair< std::string , std::string > > & types_and_filters 
)
{
	// Get window handle:

	HWND handle = 0; if ( window != 0 ) handle = window->GetWindowHandle();

    // Declare an open file name structure:   

    OPENFILENAMEA ofn = {0};

    //--------------------------------------------------------------------------
    // Figure out the size of the filter terms buffer needed for for the dialog:
    //--------------------------------------------------------------------------

    // Need two chars to begin with to terminate buffer

    unsigned filter_buf_size = 2;

    {
        std::list< std::pair<std::string,std::string> >::iterator i = types_and_filters.begin();
        std::list< std::pair<std::string,std::string> >::iterator e = types_and_filters.end();

        while ( i != e )
        {
            // Get both strings:

            std::string & s1 = (*i).first;
            std::string & s2 = (*i).second;

            // Add their lenght to the lenght of the buffer:

            filter_buf_size += s1.size();
            filter_buf_size += s2.size();

            // Add null terminating chars for both strings to lenght of buffer:

            filter_buf_size += 2;

            // Move onto the next pair of strings

            ++i;

        }   // end for all filter terms
    }

    //--------------------------------------------------------------------------
    // Make up the filter buffer and populate it:
    //--------------------------------------------------------------------------

    char * filter_buf = new char[ filter_buf_size ];

    // Populate the filter buffer:

    {
        // Store current buffer position here

        char * buf_pos = filter_buf;

        // Copy all the strings into the buffer

        std::list< std::pair<std::string,std::string> >::iterator i = types_and_filters.begin();
        std::list< std::pair<std::string,std::string> >::iterator e = types_and_filters.end();

        while ( i != e )
        {
            // Get both strings:

            std::string & s1 = (*i).first;
            std::string & s2 = (*i).second;

            // Copy 1st string into buffer:

            memcpy( buf_pos , s1.data() , s1.size() ); buf_pos += s1.size();

            // Null terminate after 1st string:

            * buf_pos = 0; buf_pos++;

            // Copy 2nd string into buffer:

            memcpy( buf_pos , s2.data() , s2.size() ); buf_pos += s2.size();

            // Null terminate after 2nd string:

            * buf_pos = 0; buf_pos++;

            // Move onto the next pair of strings

            ++i;

        }   // end for all filter terms

        // Add last two null terminating characters in:

        buf_pos[0] = 0;
        buf_pos[1] = 0;
    }

    //--------------------------------------------------------------------------
    // Get the chosen file:
    //--------------------------------------------------------------------------

    // Store the chosen file name here:

    static char file_name[MAX_PATH+1]; file_name[0] = 0;

    // Fill in the required fields:

    ofn.lStructSize      = sizeof(OPENFILENAMEA);   // fill in structure size
    ofn.hwndOwner        = handle;					// window that owns the dialog
    ofn.lpstrFile        = file_name;				// buffer to dump file name into
    ofn.lpstrFilter      = filter_buf;				// Filter to use for the dialog
    ofn.lpstrTitle       = title.data();            // Title for the dialog
    ofn.nMaxFile         = MAX_PATH;				// Maxmimum file name lenght
    ofn.nFilterIndex     = 1;                       // Use the first filter term in the list by default
    ofn.Flags           |= OFN_LONGNAMES;           // Use long name format not 8.3
    ofn.Flags           |= OFN_NOCHANGEDIR;         // Don't allow working dir to be changed
    ofn.Flags           |= OFN_FILEMUSTEXIST;       // File must exist

    if ( start_dir.size() > 0 )
    {
        // Set starting directory of the dialog

        ofn.lpstrInitialDir = start_dir.data();
    }

    // Try and open a file:

    if ( GetOpenFileNameA( &ofn ) != 0 )
    {
        // File choosen: return the file choosen:

        return std::string(file_name);
    }
    else
    {
        // No file chosen: return a blank string

        return std::string("");
    }
}

//=====================================================================================================================
/// @brief		Shows a file save dialog.
/// @param		window - owner window of the dialog. if null then dialog is not blocking.
/// @param		title - title for the dialog box
/// @param		start_dir - directory to start in
/// @param		types_and_filters - list containing pairs of file type names and filters
/// @returns	name of file user wants to save to or a zero length string if none was specified
//=====================================================================================================================

std::string Dialogs::ShowSaveFileBox
( 
	Window * window , 
	std::string title , 
	std::string start_dir , 
	std::list< std::pair< std::string , std::string > > & types_and_filters 
)
{
	// Get window handle:

	HWND handle = 0; if ( window != 0 ) handle = window->GetWindowHandle();

    // Declare an open file name structure:   

    OPENFILENAMEA ofn = {0};

    //--------------------------------------------------------------------------
    // Figure out the size of the filter terms buffer needed for for the dialog:
    //--------------------------------------------------------------------------

    // Need two chars to begin with to terminate buffer

    unsigned filter_buf_size = 2;

    {

        std::list< std::pair<std::string,std::string> >::iterator i = types_and_filters.begin();
        std::list< std::pair<std::string,std::string> >::iterator e = types_and_filters.end();

        while ( i != e )
        {
            // Get both strings:

            std::string & s1 = (*i).first;
            std::string & s2 = (*i).second;

            // Add their lenght to the lenght of the buffer:

            filter_buf_size += s1.size();
            filter_buf_size += s2.size();

            // Add null terminating chars for both strings to lenght of buffer:

            filter_buf_size += 2;

            // Move onto the next pair of strings

            ++i;

        }   // end for all filter terms
    }

    //--------------------------------------------------------------------------
    // Make up the filter buffer and populate it:
    //--------------------------------------------------------------------------

    char * filter_buf = new char[ filter_buf_size ];

    // Populate the filter buffer:

    {
        // Store current buffer position here

        char * buf_pos = filter_buf;

        // Copy all the strings into the buffer

        std::list< std::pair<std::string,std::string> >::iterator i = types_and_filters.begin();
        std::list< std::pair<std::string,std::string> >::iterator e = types_and_filters.end();

        while ( i != e )
        {
            // Get both strings:

            std::string & s1 = (*i).first;
            std::string & s2 = (*i).second;

            // Copy 1st string into buffer:

            memcpy( buf_pos , s1.data() , s1.size() ); buf_pos += s1.size();

            // Null terminate after 1st string:

            * buf_pos = 0; buf_pos++;

            // Copy 2nd string into buffer:

            memcpy( buf_pos , s2.data() , s2.size() ); buf_pos += s2.size();

            // Null terminate after 2nd string:

            * buf_pos = 0; buf_pos++;

            // Move onto the next pair of strings

            ++i;

        }   // end for all filter terms

        // Add last two null terminating characters in:

        buf_pos[0] = 0;
        buf_pos[1] = 0;
    }

    //--------------------------------------------------------------------------
    // Get the chosen file:
    //--------------------------------------------------------------------------

    // Store the chosen file name here:

    static char chosen_file_name[MAX_PATH+1]; chosen_file_name[0] = 0;

    // Store the chosen filter here:

    static char chosen_filter[MAX_PATH+1];

    chosen_filter[0] = 0;
    chosen_filter[1] = 0;
    chosen_filter[2] = 0;

    // Fill in the required fields:

    ofn.lStructSize       = sizeof(OPENFILENAMEA);		// fill in structure size
    ofn.hwndOwner         = handle;						// window that owns the dialog
    ofn.lpstrFile         = chosen_file_name;			// buffer to dump file name into
    ofn.lpstrCustomFilter = chosen_filter;				// Where to save the chosen filter
    ofn.lpstrFilter       = filter_buf;					// Filter to use for the dialog
    ofn.lpstrTitle        = title.data();				// Title for the dialog
    ofn.nMaxFile          = MAX_PATH;					// Maxmimum file name lenght
    ofn.nMaxCustFilter    = MAX_PATH + 1;				// Maximum size for chosen filter
    ofn.nFilterIndex      = 1;							// Use the first filter term in the list by default
    ofn.Flags            |= OFN_LONGNAMES;				// Use long name format not 8.3
    ofn.Flags            |= OFN_NOCHANGEDIR;			// Don't allow working dir to be changed
    ofn.Flags            |= OFN_OVERWRITEPROMPT;		// Prompt if over-writing things

    if ( start_dir.size() > 0 )
    {
        // Set starting directory of the dialog

        ofn.lpstrInitialDir = start_dir.data();
    }

    // Try and open a file:

    if ( GetSaveFileNameA( &ofn ) )
    {
        // Get the filter term chosen:

        std::string filter_term = chosen_filter + 1;

        // Make a string for the chosen file name:

        std::string name = chosen_file_name;

        // See if an extension was chosen:

        if ( filter_term.size() )
        {
            // Strip the filter term of all characters before the .extension part

            std::string chosen_extension;

            if ( filter_term.rfind("*") != std::string::npos )
            {
                chosen_extension = filter_term.data() + filter_term.rfind("*") + 1;
            }

            // See if the file name already contains the extension:

            if ( name.rfind(chosen_extension) == std::string::npos )
            {
                // See if the user put in a different extension

                if ( name.rfind(".") == std::string::npos )
                {
                    // No extension put in by the user: append the extension to the file name

                    name += chosen_extension;
                }
            }
        }

        // File choosen: return the file choosen:

        return std::string(name);
    }
    else
    {
        // No file chosen: return a blank string

        return std::string("");
    }
}
