/*
	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		Allows for querying of mouse input and also for manipulation of the mouse.
//=====================================================================================================================

#include "Precompiled.h"
#include "Input\Mouse.h"
#include "Windows\Window.h"

using namespace Game;

//=====================================================================================================================
/// @brief		Tells if the mouse button of the given virtual key code is pressed
/// @param		button_code - virtual key code of the mouse button
/// @returns	true if the button is pressed
//=====================================================================================================================

bool Mouse::IsButtonPressed( Button button_code )
{
    // Return whether the key is pressed or not

    return ( (GetAsyncKeyState((int)button_code) & 0x80000000) != 0 ? true : false );	
}

//=====================================================================================================================
/// @brief		Gets the mouse position in screen coordinates
/// @param		screen_x - where to save screen position x coord
/// @param		screen_y - where to save screen position y coord
//=====================================================================================================================

void Mouse::GetScreenPosition( int & screen_x , int & screen_y )
{
	POINT p = {0}; GetCursorPos(&p);
	
	screen_x = p.x;
	screen_y = p.y;
}

//=====================================================================================================================
/// @brief		Get the position of the mouse in client coordinates:
/// @param		window - window to get position of mouse in client coordinates
/// @param		client_x - where to save the x coordinate
/// @param		client_y - where to save the y coordinate
/// @pre		Given window must not be null
//=====================================================================================================================

void Mouse::GetClientPosition( Window * window , int & client_x , int & client_y )
{
	// Make sure ok:
	
	ENSURE( window , "Given window must not be null" );

	// Get the screen position:
	
	GetScreenPosition( client_x , client_y );
	
	// To client coordinates:
	
	Vec2i client_pos = window->ToClientCoords( Vec2i(client_x,client_y) );
	
	client_x = client_pos.x;
	client_y = client_pos.y;
}

//=====================================================================================================================
/// @brief		Unrestricts mouse movement if it has been restricted to the Ogre window.
//=====================================================================================================================

void Mouse::Unrestrict()
{
    // Un restrict the mouse movement

    ClipCursor(0);		
}

//=====================================================================================================================
/// @brief		Restricts the mouse to the client area of the ogre window
/// @param		window - window to restrict to
/// @pre		Given window must not be null
/// @remarks	If the window moves or changes size, this function needs to be called again. 
///				The mouse does not track the state of the current window. I.E this region 
///				will remain constant thereafter.
//=====================================================================================================================

void Mouse::RestrictToWindow( Window * window )
{
	// Make sure ok:
	
	ENSURE( window , "Given window must not be null" );
	
	// Get the size of the windows client area:
	
	Vec2u client_area = window->GetClientSize();
	
	// Get the position of the window's client area in screen coordinates:
	
	Vec2i window_client_pos = window->ToClientCoords( Vec2i::Zero() );
	
	// Calculate the coordinates of the area we will restrict the mouse to in screen coords:
	
	int lx = window_client_pos.x;
	int rx = window_client_pos.x + client_area.x;
	int ty = window_client_pos.y;
	int by = window_client_pos.y + client_area.y;	

	// Makeup a rectangle for the mouse to restrict its movement:

	RECT r = { lx, ty, rx, by, };

	// Restrict the mouse movement to this rectangle

	ClipCursor(&r);
}

//=====================================================================================================================
/// @brief		Centers the mouse in the middle of the ogre window
/// @param		window - window to restrict to
/// @pre		Given window must not be null
//=====================================================================================================================
				
void Mouse::CenterInWindow( Window * window )
{
	// Make sure ok:
	
	ENSURE( window , "Given window must not be null" );
	
	// Get the size of the window:
	
	Vec2u client_size = window->GetClientSize();
	
	// Calc screen center
	
	client_size /= 2;
	
	// Move to the center:
	
	MoveToClientPosition( window , client_size.x , client_size.y );
}

//=====================================================================================================================
/// @brief		Tells whether the mouse is in the client area of the ogre window
/// @param		window - window to check if in the client area of
/// @pre		Given window must not be null
/// @returns	True if the mouse is in the client area of the window
//=====================================================================================================================

bool Mouse::InClientArea( Window * window )
{
	// Make sure ok:
	
	ENSURE( window , "Given window must not be null" );

	// If the window is closed then it cannot be:
	
	if ( window->Exists() == false ) return false;
	
	// Get the mouse position in client coords:
	
	int client_x;
	int client_y;
	
	GetClientPosition(window,client_x,client_y);
	
	// Get the size of the window's client area:
	
	Vec2u client_size = window->GetClientSize();

	// See if within bounds:

	if ( client_x < 0						) return false;
	if ( client_y < 0						) return false;
	if ( client_x >= (int) client_size.x	) return false;
	if ( client_y >= (int) client_size.y	) return false;

	// If we got to here then it's in bounds:

	return true;
}

//=====================================================================================================================
/// @brief		Moves the mouse to a given point in screen coordinates
/// @param		screen_x - where to move to (x coord)
/// @param		screen_y - where to move to (y coord)
/// @remarks	If the point given is beyond the bounds of the screen it is clamped to the screen edges
//=====================================================================================================================

void Mouse::MoveToScreenPosition( int screen_x , int screen_y )
{
    // Get the size of the display
    
    Vec2u screen_size = Window::GetScreenSize();
    
    // Make sure the point is within the bounds of the screen:
    
    if ( screen_x < 0						) screen_x = 0;
    if ( screen_y < 0						) screen_y = 0;
    if ( screen_x >= (int) screen_size.x	) screen_x = screen_size.x - 1;
    if ( screen_y >= (int) screen_size.y	) screen_y = screen_size.y - 1;
    
    // Transform to normalised device coords between 0-65535:
    
    unsigned normalised_x = screen_x;
    unsigned normalised_y = screen_y;
    
    normalised_x *= 0xffff;
    normalised_y *= 0xffff;
    
    normalised_x /= screen_size.x - 1;
    normalised_y /= screen_size.y - 1;

    // Move the mouse to the new position:

    mouse_event
    (
        MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE,    // flags: move the mouse and give absolute position
        normalised_x,								// mouse x
        normalised_y,								// mouse y
        0,                                          // amount of wheel movement
        0                                           // extra application info
    );   
}

//=====================================================================================================================
/// @brief		Moves the mouse to a given point in client coordinates
/// @param		window - window to move relative to
/// @param		client_x - x position to move to in client coords
/// @param		client_y - y position to move to in client coords
/// @pre		Given window must not be null
/// @remarks	Movement will be clamped if an attempt is made to move the mouse off the screen
//=====================================================================================================================

void Mouse::MoveToClientPosition( Window * window , int client_x , int client_y )
{
	// Make sure ok:
	
	ENSURE( window , "Given window must not be null" );
	
	// Convert to screen coords:
	
	Vec2i screen_pos = window->ToScreenCoords( Vec2i(client_x,client_y) );
	
	// Move to that position:
	
	MoveToScreenPosition(screen_pos.x,screen_pos.y);
}

//=====================================================================================================================
/// @brief		Sets the current cursor in use
/// @param		window - window to set the cursor for
/// @param		type - type of cursor to use
/// @pre		Given window must not be null
//=====================================================================================================================

void Mouse::SetMouseCursor( Window * window , CusorType type )
{
	// Make sure ok:
	
	ENSURE( window , "Given window must not be null" );
	
	// Get the window handle:
	
	HWND window_handle = (HWND) window->GetWindowHandle();
	
	// Right set it:
	
	if ( type == Mouse::CURSOR_NONE )
	{
		SetClassLong( window_handle , GCL_HCURSOR , (LONG) LoadIconA( GetModuleHandle(0) , "BLANK_CURSOR" ) );
	}
	else if ( type == Mouse::CURSOR_ARROW )
	{
		SetClassLong( window_handle , GCL_HCURSOR , (LONG) LoadCursorA(0,IDC_ARROW) );
	}
	else
	{
		SetClassLong( window_handle , GCL_HCURSOR , (LONG) LoadCursorA(0,IDC_CROSS) );
	}
}
