#include ".\RawController.h"

// Initializes an instance of the RawController class
RawController::RawController(void)
{
  mConnected = false;
  for ( int i = 0; i < AXIS_MAX; i++ )
  {
    mAxis[i] = 0;
  }
  for ( int i = 0; i < BUTTON_MAX; i++ )
  {
    mButton[i] = 0;
  }
}

// Gets the current value for the specified axis.
int RawController::GetAxis( int axis )
{
  return mAxis[axis];
}

// Gets the number of axes on this joystick.
int RawController::GetAxisCount()
{
  return AXIS_MAX;
}

// Gets the minimum value for the specified axis.
int RawController::GetAxisMin( int axis )
{
  return -10000;
}

// Gets the maximum value for the specified axis.
int RawController::GetAxisMax( int axis )
{
  return +10000;
}

// Gets the current value for the specified button.
int RawController::GetButton( int button )
{
  return mButton[button];
}

// Gets the number of axes on this joystick.
int RawController::GetButtonCount()
{
  return BUTTON_MAX;
}

// Gets a bitmask that represents the state of all buttons on the joystick.
// bit 0 represents button 0, bit 1 represents button 1, etc.
int RawController::GetButtonStates()
{
  int buttonStates = 0;
  for ( int i = 0; i < BUTTON_MAX; i++ )
  {
    if ( mButton[i] )
    {
      buttonStates |= (1<<i);
    }
  }
  return buttonStates;
}

// Gets a value that indicates whether the specified joystick is connected
// and functioning.
bool RawController::GetConnected()
{
  return mConnected;
}

// Sets the current value for the specified axis.
void RawController::SetAxis( int axis, int value )
{
  mAxis[axis] = value;
}

// Sets the current value for the specified button.
void RawController::SetButton( int button, int value )
{
  mButton[button] = value;
}

// Sets a value that indicates whether the specified joystick is connected
// and functioning.
void RawController::SetConnected( bool connected )
{
  mConnected = connected;
}

// Converts a POV value to an array of d-pad button states
// pov - angle of the pov in hundreths of degrees, -1 for centered
// buttons - the array of buttons to set u,r,d,l
/*static*/ void RawController::POVtoDPAD( int pov, int buttons[4] )
{
  int octant[9][4] =
  {
    // u,r,d,l
    {1,0,0,0},
    {1,1,0,0},
    {0,1,0,0},
    {0,1,1,0},
    {0,0,1,0},
    {0,0,1,1},
    {0,0,0,1},
    {1,0,0,1},
    {0,0,0,0}, // centered
  };

  int index;
  if ( pov == -1 )
  {
    // pov is centered
    index = 8;
  }
  else
  {
    pov += 2250;
    if ( pov >= 36000 )
    {
      pov -= 36000;
    }
    index = pov / 4500;
  }

  for ( int i = 0; i < 4; i++ )
  {
    buttons[i] = octant[index][i];
  }
}

