import $ from './jQuery';
import adFixCode from './adFixCode';
const initUtag = function initUtag(utagData, opts = {}) {
  const {
    ads = true
  } = opts;
  return new Promise((resolve, reject) => {
    if (typeof window === 'undefined' || window.UTAG_SCRIPTS_LOADED === true || !ads) {
      resolve();
      return;
    }
    window.jQuery = $;
    window.$ = $;

    /* eslint-disable-next-line no-console */
    console.log('\n\nInitializing Utag\n\n');
    window.utag_data = utagData;
    const utagScript = window.document.createElement('script');
    utagScript.src = '//tags.tiqcdn.com/utag/politico/main/prod/utag.js';
    utagScript.type = 'text/javascript';
    utagScript.async = true;
    const firstScriptTag = window.document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(utagScript, firstScriptTag);

    // Ad Fix Code
    adFixCode();
    let intervalCount = 0;
    const interval = setInterval(() => {
      if (intervalCount === 30) {
        clearInterval(interval);
        reject(new Error('UTag Timeout: Too much time has passed, utag still not loaded.'));
      }
      if (window.utag) {
        resolve();
      }
      intervalCount += 1;
    }, 500);
  });
};
export default initUtag;