/* jshint node: true */
'use strict';

var Funnel = require('broccoli-funnel');
var mergeTrees = require('broccoli-merge-trees');

module.exports = {
  name: 'ember-google-publisher-tags',

  contentFor: function(type, config) {
    if (type === 'head-footer' && !this.app.options.gptIframeJail) {
      return `
<script type='text/javascript'>
  var googletag = googletag || {};
  googletag.cmd = googletag.cmd || [];
  (function() {
    var gads = document.createElement('script');
    gads.async = true;
    gads.type = 'text/javascript';
    var useSSL = 'https:' == document.location.protocol;
    gads.src = (useSSL ? 'https:' : 'http:') +
      '//www.googletagservices.com/tag/js/gpt.js';
    var node = document.getElementsByTagName('script')[0];
    node.parentNode.insertBefore(gads, node);
  })();
</script>
      `;
    }
  },

  config: function(env, config) {
    if (this.app) {
      // TODO: `this.app` check is necessary for "ember serve", but not "ember build": why?
      this.app.options.gptIframeJail = config.gpt && config.gpt.iframeJail;
    }
  },

  treeForPublic: function(tree) {
    if (this.app.options.gptIframeJail) {
      var assetsTree = new Funnel('public');
      return mergeTrees([tree, assetsTree], {
        overwrite: true
      });
    }
  }
};

/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-google-publisher-tags',

  contentFor: function(type, config) {
    if (type === 'head-footer' && !this.gptIframeJail) {
      return `
<script type='text/javascript'>
  var googletag = googletag || {};
  googletag.cmd = googletag.cmd || [];
  (function() {
    var gads = document.createElement('script');
    gads.async = true;
    gads.type = 'text/javascript';
    var useSSL = 'https:' == document.location.protocol;
    gads.src = (useSSL ? 'https:' : 'http:') +
      '//www.googletagservices.com/tag/js/gpt.js';
    var node = document.getElementsByTagName('script')[0];
    node.parentNode.insertBefore(gads, node);
  })();
</script>
      `;
    }
  },

  config: function(env, config) {
    this.gptIframeJail = config.gpt && config.gpt.iframeJail;
  },

  treeForPublic: function(tree) {
    if (this.gptIframeJail) {
      return tree;
    }
  }
};

Fix iframeJail option when serving an app in ember@2.16.0+
Fix iframeJail option when serving an app in ember@2.16.0+

The treeForPublic hook runs before the app is initialized, so the iframeJail
option was not being read at all. This commit removes the reliance on the app
and simply reads the config, making it available in the current context.
