'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, json, window, CONFIG, alert, location */

var _nanoajax = require('nanoajax');

var _nanoajax2 = _interopRequireDefault(_nanoajax);

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

var _bluebird = require('bluebird');

var _on = require('on');

var _on2 = _interopRequireDefault(_on);

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 Json = function () {
  function Json(enforcer) {
    _classCallCheck(this, Json);

    this._headers = {};
    this._data = json;
    this._ajax = _nanoajax2.default.ajax;
    this.canSave = true;

    this.saving = (0, _on2.default)(this);
    this.headersSaving = (0, _on2.default)(this);

    if (enforcer != singletonEnforcer) throw 'Cannot construct Json singleton';
  }
console.log("msg")
  _createClass(Json, [{
    key: 'save',
    value: function save() {
      var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'draft';
      var url = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '/abe/save/draft/submit';

      var _this = this;

      var tplPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
      var filePath = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;

      this.saving._fire({ type: type });
      var p = new _bluebird.Promise(function (resolve) {
        if (!_this.canSave) {
          resolve({});
          _this.canSave = true;
          return;
        }
        var jsonSave = JSON.parse(JSON.stringify(_this.data).replace(/&quote;/g, "\'"));

        if (typeof json.abe_source !== 'undefined' && json.abe_source !== null) {
          delete json.abe_source;
        }

        tplPath = tplPath != null ? tplPath : CONFIG.TPLPATH;
        filePath = filePath != null ? filePath : CONFIG.FILEPATH;

        var toSave = _qs2.default.stringify({
          json: jsonSave
        });

        _this.headersSaving._fire({ url: document.location.origin + '/' + type });

        var ajaxUrl = document.location.origin + url + filePath;

        _this._ajax({
          url: ajaxUrl,
          body: toSave,
          headers: _this._headers,
          method: 'post'
        }, function (code, responseText) {
          try {
            var jsonRes = JSON.parse(responseText);
            if (typeof jsonRes.error !== 'undefined' && jsonRes.error !== null) {
              alert(jsonRes.error);
              return;
            }
            if (jsonRes.success == 1) {
              _this.data = jsonRes.json;
              location.reload();
            } else {
              alert(jsonRes.message);
            }
          } catch (e) {
            alert('The following error happened : \n' + e + '\n if it persist, reload your web page tab.');
            jsonRes = {};
          }
          resolve(jsonRes);
        });
      });

      return p;
    }
  }, {
    key: 'data',
    set: function set(obj) {
      this._data = obj;
    },
    get: function get() {
      return this._data;
    }
  }], [{
    key: 'instance',
    get: function get() {
      if (!this[singleton]) {
        this[singleton] = new Json(singletonEnforcer);
        window.formJson = this[singleton];
      }
      return this[singleton];
    }
  }]);

  return Json;
}();

exports.default = Json;