namespace kos_gfx
{
	namespace input
	{
		struct controller_state
		{
			kos_gfx::Uint32 buttons;
			kos_gfx::Uint32 last_buttons;
			kos_gfx::Uint32 clicked_buttons;
			kos_gfx::Uint8 r_trigger; //0 if not pressed, 255 if all down ;-);
			kos_gfx::Uint8 l_trigger; //same here ;-);
			kos_gfx::Sint8 joystick_x; //-128 if all left, +127 if all right;
			kos_gfx::Sint8 joystick_y; //-128 if all up, +127 if all down;
			bool connected;
			
			controller_state():buttons(0),last_buttons(0),clicked_buttons(0),r_trigger(0),l_trigger(0)
			,joystick_x(0),joystick_y(0),connected(false)
			{};
		};
		
		maple_device_t* controller_devs[4];
		controller_state controllers[4];
		kos_gfx::Uint8 NUMBER_OF_CONTROLLERS;
		bool emulate_dpad=false;
	
		const kos_gfx::Uint32 BUTTON_LEFT=CONT_DPAD_LEFT;
		const kos_gfx::Uint32 BUTTON_RIGHT=CONT_DPAD_RIGHT;
		const kos_gfx::Uint32 BUTTON_UP=CONT_DPAD_UP;
		const kos_gfx::Uint32 BUTTON_DOWN=CONT_DPAD_DOWN;
		const kos_gfx::Uint32 BUTTON_A=CONT_A;
		const kos_gfx::Uint32 BUTTON_B=CONT_B;
		const kos_gfx::Uint32 BUTTON_X=CONT_X;
		const kos_gfx::Uint32 BUTTON_Y=CONT_Y;
		const kos_gfx::Uint32 BUTTON_START=CONT_START;
	
		void init()
		{
			for(kos_gfx::Uint8 i=0;i<4;++i)
			{
				controller_devs[i]=maple_enum_type(i, MAPLE_FUNC_CONTROLLER);
				if(!controller_devs[i])
				{
					controller_devs[i]=NULL;
					NUMBER_OF_CONTROLLERS=i;
					break;
				}
				else
				{
					controllers[i].connected=true;
				};
			};
		};
	
		void shutdown()
		{
			//nothing here yet ;-);
		};
		
		void update()
		{
			for(int i=0;i<NUMBER_OF_CONTROLLERS;++i)
			{
				cont_state_t *state=(cont_state_t*)maple_dev_status(controller_devs[i]);
				if(state==NULL)
				{
					controllers[i].connected=false;
					continue;
				};
				
				controllers[i].connected=true;
				controllers[i].buttons=state->buttons;
				
				if(emulate_dpad)
				{
					if(state->joyx>64)
						controllers[i].buttons|=BUTTON_RIGHT;
					if(state->joyy>64)
						controllers[i].buttons|=BUTTON_DOWN;
					if(state->joyx<-63)
						controllers[i].buttons|=BUTTON_LEFT;
					if(state->joyy<-63)
						controllers[i].buttons|=BUTTON_UP;
				};
			
				//the clicked buttons are those that were clicked last time, yet are not anymore, therefore: ;-);
				controllers[i].clicked_buttons=(controllers[i].buttons^controllers[i].last_buttons)&controllers[i].last_buttons;
				controllers[i].last_buttons=controllers[i].buttons;
			
				controllers[i].r_trigger=state->rtrig;
				controllers[i].l_trigger=state->ltrig;
				controllers[i].joystick_x=state->joyx;
				controllers[i].joystick_y=state->joyy;
			};
		};
		
		void reset(kos_gfx::Uint8 con_id)
		{
			if(con_id<4)
				controllers[con_id]=controller_state();
		};
		
		void reset_all()
		{
			for(int i=0;i<4;++i)
				kos_gfx::input::reset(i);
		};
		
	};
};
