/*
 Copyright (c) 2010, The Barbarian Group
 All rights reserved.

 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 and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
*/

#include "cinder/app/AppImplOFBasic.h"
#include "cinder/app/AppBasic.h"
#include "cinder/app/AppImplOFRenderer.h"
#include "cinder/app/Renderer.h"


using std::vector;
using std::string;

#define LOSHORT(l)           ((SHORT)(l))
#define HISHORT(l)           ((SHORT)(((DWORD)(l) >> 16) & 0xFFFF))

namespace cinder { namespace app {


AppImplOFBasic::AppImplOFBasic( AppBasic *aApp )
	: AppImplOF( aApp ), mApp( aApp ), mHasBeenInitialized( false )
{
	mShouldQuit = false;
	mIsDragging = false;
}

void AppImplOFBasic::run()
{
	mDisplay = mApp->getSettings().getDisplay();
	if( ! mDisplay )
		mDisplay = cinder::Display::getMainDisplay().get();

	if( mApp->getSettings().isFullScreen() ) {
		mFullScreen = true;
		mWindowWidth = mApp->getSettings().getFullScreenWidth();
		mWindowHeight = mApp->getSettings().getFullScreenHeight();	
	}
	else {
		mFullScreen = false;
		mWindowWidth = mApp->getSettings().getWindowWidth();
		mWindowHeight = mApp->getSettings().getWindowHeight();
	}
	
	mFrameRate = mApp->getSettings().getFrameRate();
	
	createWindow( &mWindowWidth, &mWindowHeight );
	
	//mApp->privateSetup__();
	mHasBeenInitialized = true;
	//mApp->privateResize__( mWindowWidth, mWindowHeight );

	ofRunApp(this);

	/*::ShowWindow( mWnd, SW_SHOW );
	::SetForegroundWindow( mWnd );
	::SetFocus( mWnd );
	::DragAcceptFiles( mWnd, TRUE );*/
	
	// initialize our next frame time to be definitely now
	mNextFrameTime = -1;
	
	/*MSG msg;
	while( ! mShouldQuit ) {
		if( ::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) {
			::TranslateMessage( &msg );
			::DispatchMessage( &msg ); 
		}
		double currentSeconds = mApp->getElapsedSeconds();
		if( currentSeconds >= mNextFrameTime ) {
			mNextFrameTime = currentSeconds + 1.0 / mFrameRate;
			mApp->privateUpdate__();
			::RedrawWindow( mWnd, NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW );
		}
		else
			::Sleep( 1 );
	}*/

	//killWindow( mFullScreen );
	mApp->privateShutdown__();
	delete mApp;
}

bool AppImplOFBasic::createWindow( int *width, int *height )
{
	ofSetupOpenGL(*width, *height, mFullScreen?OF_FULLSCREEN:OF_WINDOW);
	return true;
}

void AppImplOFBasic::killWindow( bool wasFullScreen )
{
	std::exit(0);
}

void AppImplOFBasic::toggleFullScreen()
{
	ofToggleFullscreen();
}

void AppImplOFBasic::setWindowWidth( int aWindowWidth )
{
	ofSetWindowShape(aWindowWidth, ofGetHeight());
}

void AppImplOFBasic::setWindowHeight( int aWindowHeight )
{
	ofSetWindowShape(ofGetWidth(), aWindowHeight);
}

void AppImplOFBasic::setWindowSize( int aWindowWidth, int aWindowHeight )
{
	ofSetWindowShape(aWindowWidth, aWindowHeight);
}

float AppImplOFBasic::setFrameRate( float aFrameRate )
{
	ofSetFrameRate(aFrameRate);
	return ofGetFrameRate();
}

void AppImplOFBasic::getScreenSize( int clientWidth, int clientHeight, int *resultWidth, int *resultHeight )
{
	*resultWidth  = ofGetScreenWidth();
	*resultHeight = ofGetScreenHeight();
}
void AppImplOFBasic::setup(){
	if(mFrameRate!=-1) ofSetFrameRate(mFrameRate);
	mApp->setup();
}

void AppImplOFBasic::update(){
	mApp->update();
}

void AppImplOFBasic::draw(){
	mApp->draw();
}

void AppImplOFBasic::mousePressed(int x, int y, int button){
	mApp->mouseDown(MouseEvent(button,x,y,0,0,0));
}

void AppImplOFBasic::mouseReleased(int x, int y, int button){
	mApp->mouseUp(MouseEvent(button,x,y,0,0,0));
}

void AppImplOFBasic::mouseDragged(int x, int y, int button){
	mApp->mouseDrag(MouseEvent(button,x,y,0,0,0));
}

void AppImplOFBasic::mouseMoved(int x, int y){
	mApp->mouseMove(MouseEvent(1,x,y,0,0,0));
}

/*
unsigned int prepMouseEventModifiers( WPARAM wParam )
{
	unsigned int result = 0;
	if( wParam & MK_CONTROL ) result |= MouseEvent::CTRL_DOWN;
	if( wParam & MK_LBUTTON ) result |= MouseEvent::LEFT_DOWN;
	if( wParam & MK_MBUTTON ) result |= MouseEvent::MIDDLE_DOWN;
	if( wParam & MK_RBUTTON ) result |= MouseEvent::RIGHT_DOWN;
	if( wParam & MK_SHIFT ) result |= MouseEvent::SHIFT_DOWN;
	if( ::GetKeyState( VK_MENU ) < 0 ) result |= MouseEvent::ALT_DOWN;	
	if( (::GetKeyState( VK_LWIN ) < 0) || (::GetKeyState( VK_RWIN ) < 0) ) result |= MouseEvent::META_DOWN;
	return result;
}

// Certain key codes need to be refined, for example VK_MENU needs to be
// converted into VK_LALT or VK_RALT
int prepNativeKeyCode( WPARAM wParam )
{
	unsigned int result = (int)wParam;
	if( wParam == VK_MENU ) {
		result = ( ::GetKeyState( VK_RMENU ) ) ? VK_RMENU : VK_LMENU;
	}
	else if( wParam == VK_SHIFT ) {
		result = ( ::GetKeyState( VK_RSHIFT ) ) ? VK_RSHIFT : VK_LSHIFT;	
	}
	else if( wParam == VK_CONTROL ) {
		result = ( ::GetKeyState( VK_RCONTROL ) ) ? VK_RCONTROL : VK_LCONTROL;		
	}
	return result;
}

char mapVirtualKey( WPARAM wParam )
{
	BYTE keyboardState[256];
	::GetKeyboardState( keyboardState );
	WORD result[4];
	
	int resultLength = ::ToAscii( wParam, ::MapVirtualKey( wParam, 0 ), keyboardState, result, 0 );
	if( resultLength == 1 )
		return (char)result[0];
	else
		return 0;
}

unsigned int prepKeyEventModifiers()
{
	unsigned int result = 0;
	if( ::GetKeyState( VK_CONTROL ) & 0x8000 ) result |= KeyEvent::CTRL_DOWN;
	if( ::GetKeyState( VK_SHIFT ) & 0x8000 ) result |= KeyEvent::SHIFT_DOWN;
	if( ( ::GetKeyState( VK_LMENU ) & 0x8000 ) || ( ::GetKeyState( VK_RMENU ) & 0x8000 ) ) result |= KeyEvent::ALT_DOWN;	
	if( ( ::GetKeyState( VK_LWIN ) < 0 ) || ( ::GetKeyState( VK_RWIN ) < 0 ) ) result |= KeyEvent::META_DOWN;
	return result;
}

extern "C" {
LRESULT CALLBACK WndProc(	HWND	mWnd,			// Handle For This Window
							UINT	uMsg,			// Message For This Window
							WPARAM	wParam,			// Additional Message Information
							LPARAM	lParam)			// Additional Message Information
{
	AppImplOFBasic* impl = 0;
	
	// if the message is WM_NCCREATE we need to hide 'this' in the window long
	if( uMsg == WM_NCCREATE ) {
		impl = reinterpret_cast<AppImplOFBasic*>(((LPCREATESTRUCT)lParam)->lpCreateParams);
		::SetWindowLongPtr( mWnd, GWL_USERDATA, (__int3264)(LONG_PTR)impl ); 
	}
	else // the warning on this line is harmless
		impl = reinterpret_cast<AppImplOFBasic*>( ::GetWindowLongPtr( mWnd, GWL_USERDATA ) );

	if( ! impl )
		return DefWindowProc( mWnd, uMsg, wParam, lParam );		

	switch( uMsg ) {									// Check For Windows Messages
		case WM_SYSCOMMAND:							// Intercept System Commands
			switch( wParam ) {							// Check System Calls
				case SC_SCREENSAVE:					// Screensaver Trying To Start?
				case SC_MONITORPOWER:				// Monitor Trying To Enter Powersave?
					if( impl->getApp()->getSettings().getPowerManagement() )
						return 0;							// prevent
			}
		break;
		case WM_CLOSE:								// Did We Receive A Close Message?
			::PostQuitMessage(0);					// Send A Quit Message
			impl->quit();
			return 0;
		break;
		case WM_SYSKEYDOWN:
		case WM_KEYDOWN:							// Is A Key Being Held Down? 
			impl->getApp()->privateKeyDown__( KeyEvent( KeyEvent::translateNativeKeyCode( prepNativeKeyCode( (int)wParam ) ), 
					mapVirtualKey( wParam ), prepKeyEventModifiers(), (int)wParam ) );
			return 0;								// Jump Back
		break;
		case WM_SYSKEYUP:
		case WM_KEYUP:								// Has A Key Been Released?
			impl->getApp()->privateKeyUp__( KeyEvent( KeyEvent::translateNativeKeyCode( prepNativeKeyCode( (int)wParam ) ), 
					mapVirtualKey( wParam ), prepKeyEventModifiers(), (int)wParam ) );
			return 0;								// Jump Back
		break;
		
		// mouse events
		case WM_LBUTTONDOWN:
			::SetCapture( mWnd );
			impl->mIsDragging = true;
			impl->getApp()->privateMouseDown__( MouseEvent( MouseEvent::LEFT_DOWN, LOSHORT(lParam), HISHORT(lParam), prepMouseEventModifiers( wParam ), 0.0f, static_cast<unsigned int>( wParam ) ) );
			return 0;
		break;
		case WM_RBUTTONDOWN:
			::SetCapture( mWnd );
			impl->mIsDragging = true;
			impl->getApp()->privateMouseDown__( MouseEvent( MouseEvent::RIGHT_DOWN, LOSHORT(lParam), HISHORT(lParam), prepMouseEventModifiers( wParam ), 0.0f, static_cast<unsigned int>( wParam ) ) );
			return 0;
		break;		
		case WM_MBUTTONDOWN:
			::SetCapture( mWnd );
			impl->mIsDragging = true;		
			impl->getApp()->privateMouseDown__( MouseEvent( MouseEvent::MIDDLE_DOWN, LOSHORT(lParam), HISHORT(lParam), prepMouseEventModifiers( wParam ), 0.0f, static_cast<unsigned int>( wParam ) ) );
			return 0;
		break;
		case WM_LBUTTONUP:
			::ReleaseCapture();
			impl->mIsDragging = false;		
			impl->getApp()->privateMouseUp__( MouseEvent( MouseEvent::LEFT_DOWN, LOSHORT(lParam), HISHORT(lParam), prepMouseEventModifiers( wParam ), 0.0f, static_cast<unsigned int>( wParam ) ) );
			return 0;
		break;
		case WM_RBUTTONUP:
			::ReleaseCapture();
			impl->mIsDragging = false;		
			impl->getApp()->privateMouseUp__( MouseEvent( MouseEvent::RIGHT_DOWN, LOSHORT(lParam), HISHORT(lParam), prepMouseEventModifiers( wParam ), 0.0f, static_cast<unsigned int>( wParam ) ) );
			return 0;
		break;		
		case WM_MBUTTONUP:
			::ReleaseCapture();
			impl->mIsDragging = false;	
			impl->getApp()->privateMouseUp__( MouseEvent( MouseEvent::MIDDLE_DOWN, LOSHORT(lParam), HISHORT(lParam), prepMouseEventModifiers( wParam ), 0.0f, static_cast<unsigned int>( wParam ) ) );
			return 0;
		break;
		case WM_MOUSEWHEEL:
			impl->getApp()->privateMouseWheel__( MouseEvent( 0, LOSHORT(lParam), HISHORT(lParam), prepMouseEventModifiers( wParam ),
					GET_WHEEL_DELTA_WPARAM( wParam ) / 120.0f, static_cast<unsigned int>( wParam ) ) );			
		break;
		case WM_KILLFOCUS:
			// if we lose capture during a drag, post a mouseup event as a notifier
			if( impl->mIsDragging ) {
				impl->getApp()->privateMouseUp__( MouseEvent( 0, LOSHORT(lParam), HISHORT(lParam), prepMouseEventModifiers( wParam ), 0.0f, static_cast<unsigned int>( wParam ) ) );
			}
			impl->mIsDragging = false;
		break;
		case WM_MOUSEMOVE:
			if( impl->mIsDragging ) {
				impl->getApp()->privateMouseDrag__( MouseEvent( 0, LOSHORT(lParam), HISHORT(lParam), prepMouseEventModifiers( wParam ),
						0.0f, static_cast<unsigned int>( wParam ) ) );						
}
			else
				impl->getApp()->privateMouseMove__( MouseEvent( 0, LOSHORT(lParam), HISHORT(lParam), prepMouseEventModifiers( wParam ),
						0.0f, static_cast<unsigned int>( wParam ) ) );						
		break;
		case WM_SIZE:
			if( impl->mHasBeenInitialized ) {
				impl->mWindowWidth = LOWORD(lParam);
				impl->mWindowHeight = HIWORD(lParam);
				impl->getApp()->privateResize__( impl->mWindowWidth, impl->mWindowHeight );
			}
			return 0;
		break;
		case WM_MOVE:
			if( impl->mHasBeenInitialized ) {
				impl->privateSetWindowOffset__( Vec2i( LOSHORT(lParam), HISHORT(lParam) ) );
			}
			return 0;
		break;
		case WM_DROPFILES: {
			HDROP dropH = (HDROP)wParam;
			POINT dropPoint;
			char fileName[8192];
			vector<string> files;
			
			int droppedFileCount = ::DragQueryFile( dropH, 0xFFFFFFFF, 0, 0 );
			for( int i = 0; i < droppedFileCount; ++i ) {
				::DragQueryFileA( dropH, i, fileName, 8192 );
				files.push_back( std::string( fileName ) );
			}

			::DragQueryPoint( dropH, &dropPoint );
			::DragFinish( dropH );

			FileDropEvent dropEvent( dropPoint.x, dropPoint.y, files );
			impl->getApp()->privateFileDrop__( dropEvent );
			return 0;
		}
		break;
		case WM_PAINT:
			impl->getApp()->getRenderer()->startDraw();
			impl->getApp()->draw();
			impl->getApp()->getRenderer()->finishDraw();
		break;
	}

	// unhandled messages To DefWindowProc
	return DefWindowProc( mWnd, uMsg, wParam, lParam );
}
} // extern "C"*/

} } // namespace cinder::app
