/*
SDL Joystick Test 2 v20161112
By DarkRanger <darkranger.no-ip.org>
License: GNU General Public License
*/
#include <stdio.h>
#include <stdlib.h>
#include <SDL2/SDL.h>

int main_loop = 1;
SDL_Window *window = NULL;
SDL_Joystick *js;
SDL_Event event;

int js_init()
{
    int js_num = 0;
    int i = 0;
    
    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK) < 0) {
        fprintf(stderr, "Failed to initialize SDL: %s\n", SDL_GetError());
        return 0;
    }
    
    window = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_FULLSCREEN_DESKTOP);
     
    if (window == NULL) {
        fprintf(stderr, "Failed to set video mode: %s\n", SDL_GetError());
        return 0;
    }
    
    js_num = SDL_NumJoysticks();
    
    if (js_num <= 0) {
        printf("No joystick detected.\n");
        return 0;
    }
    
    SDL_JoystickEventState(SDL_ENABLE);
    printf("%d joystick(s) were found:\n", js_num);
    
    for(i = 0; i < js_num; i++) {
        js = SDL_JoystickOpen(i);
        printf("%s\n", SDL_JoystickName(js));
    }

    return 1;
}

int events()
{
    while(SDL_PollEvent(&event)) {
        switch (event.type) {
            case SDL_WINDOWEVENT:
                if (event.window.event == SDL_WINDOWEVENT_ENTER) {
                    SDL_HideWindow(window);
                }
                break;
                
            case SDL_JOYBUTTONDOWN:
                printf("js%d Button = %d\n", event.jbutton.which, event.jbutton.button);
                break;
                
            case SDL_JOYHATMOTION:
                printf("js%d Hat = %d\n", event.jhat.which, event.jhat.hat);
                break;
                
            case SDL_JOYBALLMOTION:
                printf("js%d Ball = %d\n", event.jball.which, event.jball.ball);
                break;
                
            case SDL_JOYAXISMOTION:
                if (event.jaxis.axis > 3) {
                    break;
                }
                
                if (abs(event.jaxis.value) > 32760) {
                    printf("js%d Axis = %d\n", event.jaxis.which, event.jaxis.axis);
                }
                break;
            
            /*case SDL_KEYDOWN:
                if (event.key.keysym.sym == SDLK_q) {
                    main_loop = 0;
                }
                break;*/
                
            case SDL_QUIT:
                main_loop = 0;
                break;
        }
    }
}

int clean(int exit_status)
{
    SDL_Quit;
    exit(exit_status);
}
 
int main(int argc, char *argv[])
{
    if (js_init() == 0) {
        clean(1);
    }
    
    while(main_loop == 1) {
        events();      
    }
    
    clean(0);
}

