(function() {
  function currentWorkspaceId() {
    var workspace = window.getCurrentWorkspace ? window.getCurrentWorkspace() : null;
    return workspace ? workspace.id : null;
  }

  async function startWindowTest(operationId, payload) {
    if (!window.CrankApi || !operationId) {
      throw new Error('Window test requires an operation id.');
    }
    return window.CrankApi.runOperationTest(currentWorkspaceId(), operationId, payload);
  }

  async function startSessionTest(workspaceId, operationId, payload) {
    return window.CrankApi.runOperationTest(workspaceId || currentWorkspaceId(), operationId, payload);
  }

  async function pollSessionTest(workspaceId, sessionId) {
    return window.CrankApi.getStreamSession(workspaceId || currentWorkspaceId(), sessionId);
  }

  async function stopSessionTest(workspaceId, sessionId) {
    return window.CrankApi.stopStreamSession(workspaceId || currentWorkspaceId(), sessionId);
  }

  async function startAsyncJobTest(workspaceId, operationId, payload) {
    return window.CrankApi.runOperationTest(workspaceId || currentWorkspaceId(), operationId, payload);
  }

  async function refreshAsyncJobStatus(workspaceId, jobId) {
    return window.CrankApi.getAsyncJob(workspaceId || currentWorkspaceId(), jobId);
  }

  async function loadAsyncJobResult(workspaceId, jobId) {
    return window.CrankApi.getAsyncJobResult(workspaceId || currentWorkspaceId(), jobId);
  }

  window.CrankStreamTestRun = {
    startWindowTest: startWindowTest,
    startSessionTest: startSessionTest,
    pollSessionTest: pollSessionTest,
    stopSessionTest: stopSessionTest,
    startAsyncJobTest: startAsyncJobTest,
    refreshAsyncJobStatus: refreshAsyncJobStatus,
    loadAsyncJobResult: loadAsyncJobResult,
  };
}());
