'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*global document, window, json */

var _handlebars = require('handlebars');

var _handlebars2 = _interopRequireDefault(_handlebars);

var _nanoajax = require('nanoajax');

var _nanoajax2 = _interopRequireDefault(_nanoajax);

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

var _EditorJson = require('../modules/EditorJson');

var _EditorJson2 = _interopRequireDefault(_EditorJson);

var _iframe = require('../utils/iframe');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var singleton = Symbol();
var singletonEnforcer = Symbol();

var Reload = function () {
  function Reload(enforcer) {
    _classCallCheck(this, Reload);

    this._ajax = _nanoajax2.default.ajax;
    this._json = _EditorJson2.default.instance;

    if (enforcer != singletonEnforcer) throw 'Cannot construct Reload singleton';
  }

  _createClass(Reload, [{
    key: '_nodeScriptReplace',
    value: function _nodeScriptReplace(node) {
      if (this._nodeScriptIs(node) === true) {
        node.parentNode.replaceChild(this._nodeScriptClone(node), node);
      } else {
        var i = 0;
        var children = node.childNodes;
        while (i < children.length) {
          this._nodeScriptReplace(children[i++]);
        }
      }

      return node;
    }
  }, {
    key: '_nodeScriptIs',
    value: function _nodeScriptIs(node) {
      return node.tagName === 'SCRIPT';
    }
  }, {
    key: '_nodeScriptClone',
    value: function _nodeScriptClone(node) {
      var script = document.createElement('script');
      script.text = node.innerHTML;
      for (var i = node.attributes.length - 1; i >= 0; i--) {
        script.setAttribute(node.attributes[i].name, node.attributes[i].value);
      }
      return script;
    }
  }, {
    key: 'inject',
    value: function inject(str) {
      var currentIframe = document.querySelector('#page-template');
      var sibling = currentIframe.nextElementSibling;
      var parent = sibling.parentNode;
      var iframe = document.createElement('iframe');
      var scrollTop = (0, _iframe.IframeDocument)('#page-template').body ? (0, _iframe.IframeDocument)('#page-template').body.scrollTop : 0;

      parent.classList.add('reloading');

      iframe.id = 'page-template';
      iframe.src = 'about:blank';
      iframe.sandbox = 'allow-presentation allow-modals allow-pointer-lock allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox allow-forms allow-top-navigation';
      iframe.setAttribute('data-iframe-src', document.querySelector('#page-template').getAttribute('data-iframe-src'));

      var initIframe = function initIframe() {
        var doc = iframe.contentWindow.document;
        str = str.replace(/<\/head>/, '<base href="/" /></head>');
        doc.open('text/html', 'replace');
        doc.write(str);
        doc.close();

        setTimeout(function () {
          var iframeDoc = (0, _iframe.IframeDocument)('#page-template');
          if (typeof iframeDoc !== 'undefined' && iframeDoc !== null && typeof iframeDoc.body !== 'undefined' && iframeDoc.body !== null) {
            iframeDoc.body.scrollTop = scrollTop;
          }
        }, 1000);
      };

      iframe.onload = function () {
        initIframe();
        setTimeout(function () {
          parent.classList.remove('reloading');
        }, 350);
      };

      currentIframe.remove();
      parent.insertBefore(iframe, sibling);
    }
  }, {
    key: 'reload',
    value: function reload() {
      var _this = this;

      var iframe = document.querySelector('#page-template');
      if (iframe != null) {
        var json = JSON.parse(JSON.stringify(this._json.data));
        iframe.parentNode.classList.add('reloading');

        delete json.abe_source;
        var data = _qs2.default.stringify({
          json: json
        });

        this._ajax({
          url: iframe.getAttribute('data-iframe-src'),
          body: data,
          method: 'post'
        }, function (code, responseText) {
          if (typeof responseText !== 'undefined' && responseText !== null) {
            _this.inject(responseText);
          }

          return;
        });
      }
    }
  }], [{
    key: 'instance',
    get: function get() {
      if (!this[singleton]) {
        this[singleton] = new Reload(singletonEnforcer);
        window.formJson = this[singleton];
      }
      return this[singleton];
    }
  }]);

  return Reload;
}();

exports.default = Reload;