/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2008.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: src/sgx/input/input.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/input/input.hpp"

CSGXInputManager *CSGXInputManager::m_pSingleton;

CSGXInputManager *CSGXInputManager::create()
{
	m_pSingleton = new CSGXInputManager();
	if (m_pSingleton) {
		m_pSingleton->initialize();
	}
	return m_pSingleton;
}

CSGXInputManager *CSGXInputManager::get()
{
	if (!m_pSingleton) {
		return create();
	}
	return m_pSingleton;
}

void 
CSGXInputManager::initializeGeneric()
{
}

void 
CSGXInputManager::initialize()
{
	// create original input buffers. All control data is written
	// initially into these structures. These can, potentially, be
	// platform-specific.
	const tUINT32 &controllers = getMaxControllers();
	m_pDeviceKeyboard = createKeyboard();
	m_pDeviceMouse = createMouse();

	m_pDeviceController = new CSGXInputManager::CControllerJoypad *[controllers];
    m_pController = new CSGXInputManager::CControllerJoypad *[controllers];
	for(tUINT32 i=0;i<controllers;++i) {
		m_pController[i] = new CControllerJoypad(i);	// always generic
		m_pDeviceController[i] = createJoypad(i);
	}

	m_Mapping = new tUINT32[getMaxControllers()];

	createMapping();
}

CSGXInputManager::CControllerJoypad *
CSGXInputManager::createJoypad(tUINT32 idx) {
	return new CControllerJoypad(idx);
}

CSGXInputManager::CControllerKeyboard *
CSGXInputManager::createKeyboard() {
	return new CControllerKeyboard();
}

CSGXInputManager::CControllerMouse *
CSGXInputManager::createMouse() {
	return new CControllerMouse();
}

tUINT32 
CSGXInputManager::getNumControllers()
{
	return 1;
}

tUINT32 
CSGXInputManager::getMaxControllers()
{
	return 2;
}

void 
CSGXInputManager::update(const tREAL32 telaps)
{
	// We update the buffered input, and
	// write the results back to the cross-platform version
	for(tMEM_SIZE i=0;i<getMaxControllers();i++) {
		if (m_pDeviceController[i]) {
			m_pDeviceController[i]->update(telaps, *m_pController[i]);
		}
	}

	if (m_pDeviceKeyboard) {
		m_pDeviceKeyboard->update(telaps, m_Keyboard);
	}

	if (m_pDeviceMouse) {
	   m_pDeviceMouse->update(telaps, m_Mouse);
	}
	
}

void 
CSGXInputManager::createMapping()
{
    for(tUINT32 i=0; i<getMaxControllers(); i++) {
        m_Mapping[i] = i;
    }
}

