"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.METHOD_REQUEST_OFFER_FORM_SENT = exports.METHOD_CONFIGURATION_SAVED_REMOTELY = exports.METHOD_CONFIGURATION_SAVED = exports.METHOD_ADD_TO_CART = exports.LISTENER_SWITCH_OPTIONS = exports.LISTENER_SAVE_CONFIGURATION = void 0;
exports["default"] = createMessageInterface;
var _get = _interopRequireDefault(require("lodash/get"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
var METHOD_ADD_TO_CART = exports.METHOD_ADD_TO_CART = 'addtocart';
var METHOD_CONFIGURATION_SAVED = exports.METHOD_CONFIGURATION_SAVED = 'configurationsaved';
var METHOD_REQUEST_OFFER_FORM_SENT = exports.METHOD_REQUEST_OFFER_FORM_SENT = 'requestoffer_form_sent';
var METHOD_CONFIGURATION_SAVED_REMOTELY = exports.METHOD_CONFIGURATION_SAVED_REMOTELY = 'configurationsaved_remotely';
var LISTENER_SWITCH_OPTIONS = exports.LISTENER_SWITCH_OPTIONS = 'switch_options';
var LISTENER_SAVE_CONFIGURATION = exports.LISTENER_SAVE_CONFIGURATION = 'save_configuration';

/**
 * Helper interface for bi-directional postMessage API
 */
function createMessageInterface() {
  var messageHandlers = [];
  window.addEventListener('message', function (event) {
    var typeToFind = (0, _get["default"])(event, 'data.type');
    messageHandlers.filter(function (_ref) {
      var type = _ref.type;
      return type === typeToFind;
    }).forEach(function (_ref2) {
      var handler = _ref2.handler;
      return handler(event);
    });
  }, false);
  return {
    /**
     * @param {string} type
     * @param {function(event)} handler
     */
    addListener: function addListener(type, handler) {
      messageHandlers.push({
        type: type,
        handler: handler
      });
    },
    /**
     * @param {object} messageObj
     * @param {object} [options]
     */
    dispatch: function dispatch(messageObj) {
      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var _options$targetWindow = options.targetWindow,
        targetWindow = _options$targetWindow === void 0 ? window.parent : _options$targetWindow,
        _options$targetOrigin = options.targetOrigin,
        targetOrigin = _options$targetOrigin === void 0 ? '*' : _options$targetOrigin;
      targetWindow && targetWindow.postMessage(messageObj, targetOrigin || targetWindow.origin);
    }
  };
}