/**
 * Walks all iframes with '*.twitch.tv' src and replace their
 * XMLHttpRequest with our own.
 * This facilitates using Mirage/Pretender to stub out all
 * XMLHttpRequests, even those that are delegated by Twitch.api
 * to iframes.
 *
 * This helper works for some iframes but not all. In particular
 * In works for iframes that are initialized once by global.js,
 * but not iframes which are created at run time by each test/app run.
 * Those are handled separately. grep for `xhrConstructor`.
 */
function setup() {
  let iframes = document.getElementsByTagName('iframe');
  let twitchIframes = [];
  for (let i = 0; i < iframes.length; i++) {
    let iframe = iframes[i];
    let src = iframe.src;
    let srcIncludesTwitch = src.indexOf('twitch.tv') !== -1;
    let srcIncludesTestem = src.indexOf('testem') !== -1;

    if (srcIncludesTwitch && !srcIncludesTestem) {
      let originalXHR = iframe.contentWindow.XMLHttpRequest;
      iframe.contentWindow.XMLHttpRequest = window.XMLHttpRequest;
      twitchIframes.push({iframe, originalXHR});
    }
  }

  return twitchIframes;
}

function teardown(twitchIframes=[]) {
  for (let i = 0; i < twitchIframes.length; i++) {
    let {iframe, originalXHR} = twitchIframes[i];
    iframe.contentWindow.XMLHttpRequest = originalXHR;
  }
}

export { setup, teardown };
