import { EVENT } from "../../constant";
import { v4 as uuid } from 'uuid';
export var registerSystemEvents = function registerSystemEvents(eventCenter) {
  var handleSubmitForm = function handleSubmitForm(data) {
    var attributes = data.attributes;
    var _document = document,
      body = _document.body;
    var form = document.createElement('form');
    form.setAttribute('height', '1');
    form.setAttribute('width', '1');
    Object.keys(attributes.data).forEach(function (key) {
      var input = document.createElement('input');
      input.setAttribute('type', 'hidden');
      input.setAttribute('name', key);
      input.setAttribute('value', attributes.data[key]);
      form.appendChild(input);
    });
    form.setAttribute('action', attributes.action);
    form.setAttribute('method', 'post');
    body.appendChild(form);
    setTimeout(function () {
      form.submit();
    }, 0);
  };
  var handleBeforeSubmit = function handleBeforeSubmit(data) {
    if (eventCenter.isExist(EVENT.beforeSubmit.name)) {
      eventCenter.emit(EVENT.beforeSubmit.name, data);
      return;
    }
    var eventCallbackId = uuid();
    eventCenter.dispatchToApp({
      event: EVENT.beforeSubmitDone.name,
      eventCallbackId: eventCallbackId,
      data: {
        result: 'IGNORE'
      }
    });
  };
  var handleSendBroadcast = function handleSendBroadcast(data) {
    eventCenter.dispatchToApp({
      event: EVENT.receiveBroadcast.name,
      data: data
    });
  };
  var handleSendMultiAppEventToSdk = function handleSendMultiAppEventToSdk(data) {
    eventCenter.dispatchToApp({
      event: EVENT.receiveMuitiAppFromSdk.name,
      data: data
    });
  };
  eventCenter.listen(EVENT.submitForm.name, handleSubmitForm);
  eventCenter.listen(EVENT.beforeSubmit.name, handleBeforeSubmit);
  eventCenter.listen(EVENT.sendBroadcast.name, handleSendBroadcast);
  // deprecated
  eventCenter.listen(EVENT.sendMuitiAppEventToSdk.name, handleSendMultiAppEventToSdk);
};
export var unRegisterSystemEvents = function unRegisterSystemEvents(eventCenter) {
  eventCenter.unlisten(EVENT.submitForm.name);
  eventCenter.unlisten(EVENT.beforeSubmit.name);
  eventCenter.unlisten(EVENT.sendBroadcast.name);
  eventCenter.unlisten(EVENT.sendMuitiAppEventToSdk.name);
};
export var getIframeOrigin = function getIframeOrigin(iframe) {
  var url = new URL(iframe.src);
  return url.origin;
};