/*********************************************************\
         __      __           __  __
        / /     / / _____    / / / / ______   __     __
       / /     / / /___  \  / / / / / ___  | / /    / /
      / /_____/ / _____| / / / / / / /__/ / / /    / /
     / ______  / / ___  / / / / / / _____/ / /    / /
    / /     / / / /__/ / / / / / / |____  / |____/ /
   /_/     /_/ |______/ /_/ /_/  \_____/  \_____  /
                                         ______/ /
            High Level Game Framework   /_______/

  ------------------------------------------------------

  Copyright (c) 2009 - Rodrigo Braz Monteiro.
  This file is subject to the terms of license.txt.

\*********************************************************/

#include <SDL_joystick.h>
#include "input_joystick.h"
#include "utils.h"
#include "exception.h"
using namespace Halley;


float InputJoystick::getAxis(int n)
{
	try {
		return axisAdjust(axes.at(n));
	} catch (...) {
		return 0;
	}
}

float InputJoystick::defaultAxisAdjust(float value)
{
	float absVal = abs(value);
	float sign = value >= 0 ? 1.0f : -1.0f;

	const float cutOff = 0.2f;
	if (absVal < cutOff) absVal = 0;
	else absVal = (absVal-cutOff) / (1.0f - cutOff);

	return absVal * sign;
}

size_t InputJoystick::getNumberAxes()
{
	return axes.size();
}

size_t InputJoystick::getNumberHats()
{
	return hats.size();
}

shared_ptr<InputBase> InputJoystick::getHat(int n)
{
	try {
		return hats.at(n);
	} catch (...) {
		return shared_ptr<InputBase>();
	}
}

int InputJoystick::getButtonAtPosition(char c) const
{
	bool is360 = getType() == JOYSTICK_360;
	switch (c) {
		case 'N': return is360 ? 3 : 0;
		case 'E': return is360 ? 1 : 1;
		case 'S': return is360 ? 0 : 2;
		case 'W': return is360 ? 2 : 3;
		default: throw Exception("Invalid parameter");
	}
}
