import com.jme3.app.SimpleApplication;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.input.Joystick;
import com.jme3.input.controls.AnalogListener;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
import com.jme3.system.AppSettings;

/** Force the virtual gamepad on desktop so its layout can be inspected. */
public class VirtualGamepadDemo extends SimpleApplication {
    private Geometry player;

    public static void main(String[] args) {
        VirtualGamepadDemo app = new VirtualGamepadDemo();
        AppSettings settings = new AppSettings(true);
        settings.setTitle("Virtual Gamepad | jMonkeyEngine 3.10");
        settings.setWindowSize(1120, 700);
        settings.setRenderer(AppSettings.LWJGL_OPENGL32);
        settings.setAudioRenderer(null);
        settings.setUseJoysticks(true);
        settings.setVirtualJoystick(AppSettings.VIRTUAL_JOYSTICK_ENABLED);
        settings.setVirtualJoystickDefaultLayout(AppSettings.VIRTUAL_JOYSTICK_LAYOUT_XBOX);
        app.setSettings(settings);
        app.setShowSettings(false);
        app.start();
    }

    @Override
    public void simpleInitApp() {
        setDisplayFps(false);
        setDisplayStatView(false);
        flyCam.setEnabled(false);
        viewPort.setBackgroundColor(new ColorRGBA(.055f, .075f, .11f, 1));
        cam.setLocation(new Vector3f(0, 2.8f, 9));
        cam.lookAt(Vector3f.ZERO, Vector3f.UNIT_Y);
        player = new Geometry("Player", new Box(.8f, .8f, .8f));
        Material material = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        material.setColor("Color", new ColorRGBA(1, .78f, .05f, 1));
        player.setMaterial(material);
        rootNode.attachChild(player);
        BitmapFont font = assetManager.loadFont("Interface/Fonts/Default.fnt");
        BitmapText title = new BitmapText(font);
        title.setSize(28);
        title.setColor(ColorRGBA.White);
        title.setText("VIRTUAL GAMEPAD");
        title.setLocalTranslation(420, cam.getHeight() - 36, 0);
        guiNode.attachChild(title);
        BitmapText subtitle = new BitmapText(font);
        subtitle.setSize(16);
        subtitle.setText("Touch controls use the same named input actions");
        subtitle.setLocalTranslation(390, cam.getHeight() - 76, 0);
        guiNode.attachChild(subtitle);
        Joystick[] devices = inputManager.getJoysticks();
        if (devices != null && devices.length > 0 && devices[0].getXAxis() != null) {
            devices[0].getXAxis().assignAxis("Right", "Left");
            inputManager.addListener((AnalogListener) (name, value, tpf) -> {
                if ("Left".equals(name)) player.move(-value * 2, 0, 0);
                if ("Right".equals(name)) player.move(value * 2, 0, 0);
            }, "Left", "Right");
        }
    }
}
