#ifdef TARGET_WII

#include <ultra64.h>
#include <wiiuse/wpad.h>

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <math.h>

#include "controller_api.h"

#define DEADZONE 4960

static bool init_ok;

static void controller_wii_init(void) {
}

static void controller_wii_read(OSContPad *pad) {
    //Scan Wii Mote buttons
    WPAD_ScanPads();
    u16 kDown = WPAD_ButtonsDown(0);
    u32 exp_type;
    WPAD_Probe(0, &exp_type);
	WPAD_SetDataFormat(WPAD_CHAN_0, WPAD_FMT_BTNS_ACC_IR);
    WPADData *Data = WPAD_Data(WPAD_CHAN_0); //Store data from remote 1
	WPADData data = *Data;
    WPAD_Expansion(WPAD_CHAN_0, &(data.exp)); //Get expansion data for Nunchuck support

    if (kDown & (WPAD_BUTTON_PLUS | WPAD_BUTTON_MINUS))
        pad->button |= START_BUTTON;            //PAUSE
    if (kDown & (WPAD_BUTTON_B | WPAD_NUNCHUK_BUTTON_C))
        pad->button |= Z_TRIG;                  //CROUCH
    if (kDown & WPAD_BUTTON_1)
        pad->button |= R_TRIG;                  //CAM ZOOM
    if (kDown & WPAD_BUTTON_A)
        pad->button |= A_BUTTON;                //JUMP
    if (kDown & (WPAD_BUTTON_2 | WPAD_NUNCHUK_BUTTON_Z))
        pad->button |= B_BUTTON;                //ATTACK
    if (kDown & WPAD_BUTTON_LEFT)
        pad->button |= L_CBUTTONS;              //CAM LEFT
    if (kDown & WPAD_BUTTON_RIGHT)
        pad->button |= R_CBUTTONS;              //CAM RIGHT
    if (kDown & WPAD_BUTTON_UP)
        pad->button |= U_CBUTTONS;              //CAM UP
    if (kDown & WPAD_BUTTON_DOWN)
        pad->button |= D_CBUTTONS;              //CAM DOWN
    if (kDown & WPAD_BUTTON_HOME)
        exit(0);                                //EXIT


    //MOVE MARIO
    if (exp_type == WPAD_EXP_NUNCHUK) {
        pad->stick_x = (int)data.exp.nunchuk.js.pos.x / 2;
        pad->stick_y = (int)data.exp.nunchuk.js.pos.y / 2;
    }
}

struct ControllerAPI controller_wii = {
    controller_wii_init,
    controller_wii_read
};

#endif
