package com.ygames.ysoccer.framework;

import com.badlogic.gdx.controllers.Controller;
import com.badlogic.gdx.controllers.ControllerMapping;

import static java.lang.Math.round;

class Joystick extends InputDevice {

    private Controller controller;
    private JoystickConfig config;

    Joystick(Controller controller, JoystickConfig config, int port) {
        super(Type.JOYSTICK, port);
        this.controller = controller;
        this.config = config;
    }

    @Override
    protected void read() {
        x0 = round(this.controller.getAxis(config.xAxis));
        y0 = round(this.controller.getAxis(config.yAxis));
        fire10 = this.controller.getButton(config.button1);
        fire20 = this.controller.getButton(config.button2);
        menu10 = safeGetButton(menuButton());
    }

    private int menuButton() {
        ControllerMapping mapping = controller.getMapping();
        if (mapping != null && mapping.buttonStart != ControllerMapping.UNDEFINED) {
            return mapping.buttonStart;
        }
        return config.buttonMenu;
    }

    private boolean safeGetButton(int button) {
        if (button < 0) {
            return false;
        }
        try {
            return controller.getButton(button);
        } catch (RuntimeException e) {
            return false;
        }
    }
}
