<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="../resources/webxr_util.js"></script>
<script src="../resources/webxr_test_asserts.js"></script>
<script src="../resources/webxr_test_constants.js"></script>
<script src="../resources/webxr_test_constants_fake_world.js"></script>

<script>

// 1m above world origin.
const VIEWER_ORIGIN_TRANSFORM = {
  position: [0, 1, 0],
  orientation: [0, 0, 0, 1],
};

const fakeDeviceInitParams = {
  supportedModes: ["immersive-ar"],
  views: VALID_VIEWS,
  supportedFeatures: ALL_FEATURES,
  viewerOrigin: VIEWER_ORIGIN_TRANSFORM,
};

// All test cases require anchors.
const sessionInit = { 'requiredFeatures': ['anchors'] };

// Fail the anchor creation & see if it gets communicated to the caller.
// The concrete error is not specified by the WebXR Test API / WebXR Anchors.
const anchorCreationFail = function(session, fakeDeviceController, t) {
  const debug = xr_debug.bind(this, 'anchorCreationFail');

  fakeDeviceController.setAnchorCreationCallback((parameters, controller) => {
      // Immediately fail anchor creation.
      return Promise.resolve(false);
  });

  const watcherDone = new Event("watcherdone");
  const eventWatcher = new EventWatcher(t, session, ["watcherdone"]);
  const eventPromise = eventWatcher.wait_for(["watcherdone"]);

  session.requestReferenceSpace('local').then((localRefSpace) => {
    debug("requesting animation frame");

    session.requestAnimationFrame((time, frame) => {
      debug("rAF 1");

      frame.createAnchor(new XRRigidTransform(), localRefSpace)
        .then((anchor) => {
          t.step(() => {
            assert_false(true, "Anchor creation should fail!");
          });
        })
        .catch((error) => {
          session.dispatchEvent(watcherDone);
        });

      // Anchor result will only take effect with frame data - schedule
      // a frame after we requested anchor creation, otherwise the test will time out.
      session.requestAnimationFrame(() => {
        debug("rAF 2");
      });
    });
  }); // session.requestReferenceSpace(...).then({...});

  return eventPromise;
}

xr_session_promise_test(
  "Ensures free-floating anchor creation failure is handled correctly",
  anchorCreationFail, fakeDeviceInitParams, 'immersive-ar', sessionInit);

</script>
