/*
    Robot Interface
    (C) 2006 Jason Hunt
    nulluser@gmail.com
    
    File: joystick.cpp
*/


#include <windows.h>
#include <mmsystem.h>
#include <stdio.h>

#include "joystick.h"
#include "utility.h"
#include "display.h"
#include "robot.h"
#include "input.h"


joystick_type joystick;

bool joystick_ok = false;
bool joystick_override = false; 

/* Setup joystick system */
void joystick_start( void )
{
    joystick_ok = false;

    if (joyGetNumDevs() == 0)
    {
        add_line("Unable to start joystick driver");
        return;    
    }


    JOYCAPS joystick_caps;    

    joyGetDevCaps(JOYSTICKID1, &joystick_caps, sizeof(joystick_caps));

        
    if (joystick_caps.wMid == 0)
    {
        add_line("No joystick Connected");
        return;
    }

    JOYINFO info; 
        
    if (joyGetPos(JOYSTICKID1,&info) == JOYERR_UNPLUGGED)
    {
        add_line("No joystick Connected");
        return;
    }

    joystick.base_x = info.wXpos / 65536.0;
    joystick.base_y = info.wYpos / 65536.0;
    
    joystick_ok = true;

    joystick.up = false;
    joystick.down = false;
    joystick.left = false;
    joystick.right = false;
    joystick.up_right = false;
    joystick.up_left = false;
    joystick.down_right = false;
    joystick.down_left = false;
}
/* End of start joystick */


/* Check for joystick change */
void joystick_check( void )
{
    if (!joystick_ok) return;
    
    JOYINFO info; 
        
    if (joyGetPos(JOYSTICKID1,&info) == JOYERR_UNPLUGGED)
    {
        add_line("No joystick Connected");
        return;        
    }  

    double new_x = info.wXpos / 65536.0;
    double new_y = info.wYpos / 65536.0;
    
    if (new_x == joystick.x && new_y == joystick.y)   
    {
        
        return; // no change
    }
     
    joystick.x = info.wXpos / 65536.0;
    joystick.y = info.wYpos / 65536.0;

  /*  char b[300];
    sprintf(b, "x: %f  y: %f ", joystick.x, joystick.y);
    add_line(b);*/


    unsigned int base = 1;
    
    for (int i = 0; i < 16; i++)
    {
        joystick.buttons[i] = info.wButtons & base;
        base <<= 1;
    }
 
    double x_diff = joystick.x - joystick.base_x;
    double y_diff = joystick.y - joystick.base_y;
  
    joystick.up =    (y_diff < -0.25);
    joystick.down =  (y_diff > 0.25);
    joystick.left =  (x_diff < -0.25);
    joystick.right = (x_diff > 0.25);

    input_update();
}
/* End of joystick_check */



