#ifndef IE_ADAPTER_H
#define IE_ADAPTER_H

/*
	Ripatti Artem (c) 2012
*/

#include "../core/ie_iface.h"

namespace ie
{
	class ZInputEngineAdapter : public XInputEngine
	{
		XInputEngine * _child_ie;
		//HWND h_wnd;
		int _x, _y, _sx, _sy;
		int _mx, _my;
		int _pre_x, _pre_y;
		bool _locked;
	public:
		ZInputEngineAdapter( XInputEngine * child_ie )
		{
			//h_wnd = hwnd;
			_child_ie = child_ie;
			_x = _y = _sx = _sy = 0;
			_pre_x = _mx = child_ie->get_mouse_x();
			_pre_y = _my = child_ie->get_mouse_y();
			_locked = false;
		}

		void set_state( int x, int y, int sx, int sy, bool locked )
		{
			_x = x;
			_y = y;
			_sx = sx;
			_sy = sy;
			_pre_x = _mx = _child_ie->get_mouse_x();
			_pre_y = _my = _child_ie->get_mouse_y();
			_locked = locked;
		}

		virtual void read_states()
		{
			_child_ie->read_states();
			int cur_x = _child_ie->get_mouse_x();
			int cur_y = _child_ie->get_mouse_y();
			_mx += cur_x - _pre_x;
			_my += cur_y - _pre_y;
			_pre_x = cur_x;
			_pre_y = cur_y;
			if (_locked)
			{
				if (_mx < _x) _mx = _x;
				if (_my < _y) _my = _y;
				if (_mx >= _x+_sx) _mx = _x+_sx;
				if (_my >= _x+_sy) _my = _y+_sy;
				/*POINT pnt;

				GetCursorPos(&pnt);
				ScreenToClient(h_wnd,&pnt);
				if (pnt.x < _x) pnt.x = _x;
				if (pnt.y < _y) pnt.y = _y;
				if (pnt.x >= _x+_sx) pnt.x = _x+_sx-1;
				if (pnt.y >= _y+_sy) pnt.y = _y+_sy-1;
				ClientToScreen(h_wnd,&pnt);

				SetCursorPos(pnt.x, pnt.y);*/
			}
		}

		virtual bool pressed(int key, bool before, bool now)
		{
			return _child_ie->pressed( key, before, now );
		}

		virtual bool pressed_before(int key)
		{
			return _child_ie->pressed_before( key );
		}

		virtual bool pressed_now(int key)
		{
			return _child_ie->pressed_now( key );
		}

		virtual int get_mouse_x()
		{
			/*POINT pnt;

			GetCursorPos(&pnt);
			ScreenToClient(h_wnd,&pnt);*/

			return (int)(((double)(_mx-_x)/_sx)*640.);
		}

		virtual int get_mouse_y()
		{
			/*POINT pnt;

			GetCursorPos(&pnt);
			ScreenToClient(h_wnd,&pnt);*/

			return (int)(((double)(_my-_y)/_sy)*480.);
		}

		virtual bool mouse_pressed(int button, bool before, bool now)
		{
			return _child_ie->mouse_pressed( button, before, now );
		}

		virtual bool mouse_pressed_before(int key)
		{
			return _child_ie->mouse_pressed_before( key );
		}

		virtual bool mouse_pressed_now(int key)
		{
			return _child_ie->mouse_pressed_now( key );
		}
	};
};

#endif