"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _default = function _default(api) {
  window.parent.postMessage(JSON.stringify({
    action: 'umi.ui.enable.GUmiUIFlag'
  }), '*');
  window.parent.postMessage(JSON.stringify({
    action: 'umi.ui.checkValidEditSection'
  }), '*');
  return new Promise(function (resolve, reject) {
    var messageHandler = function messageHandler(e) {
      // console.log('[Block] Received message', e.data);
      try {
        var _JSON$parse = JSON.parse(e.data),
            action = _JSON$parse.action,
            payload = _JSON$parse.payload;

        if (action === 'umi.ui.block.addBlock') {
          var position = payload;
          window.removeEventListener('message', messageHandler);
          api.showMini();
          resolve(position);
          window.parent.postMessage(JSON.stringify({
            action: 'umi.ui.disableBlockEditMode'
          }), '*');
        } else if (action === 'umi.ui.checkValidEditSection.success') {
          if (payload.haveValid) {
            api.hideMini();
            window.parent.postMessage(JSON.stringify({
              action: 'umi.ui.enableBlockEditMode'
            }), '*');
            window.parent.postMessage(JSON.stringify({
              action: 'umi.ui.changeEdit',
              payload: {
                'zh-CN': '取消编辑',
                'en-US': 'Cancel Edit'
              }
            }), '*');
          } else {
            reject(new Error('Can not find insert position'));
          }
        }
      } catch (error) {
        console.error('[Block] parse message error', error);
      }
    };

    window.addEventListener('message', messageHandler);
  });
};

exports.default = _default;