import { useEffect } from "react";
import { makeswiftConnectionCheck } from "../../../../state/builder-api/actions";
import { SharedActionTypes, makeswiftConnectionInit } from "../../../../state/shared-api";
const CONNECTION_PING_INTERVAL_MS = 20;
function useBuilderConnectionPing({ appOrigin }) {
  useEffect(() => {
    let connectionInterval;
    if (window.parent !== window) {
      window.addEventListener("message", messageHandler);
      window.parent.postMessage(makeswiftConnectionInit(), { targetOrigin: appOrigin });
    }
    return () => {
      window.removeEventListener("message", messageHandler);
      if (connectionInterval != null) {
        window.clearInterval(connectionInterval);
        connectionInterval = null;
      }
    };
    function messageHandler(event) {
      if (event.origin === appOrigin && event.data.type === SharedActionTypes.MAKESWIFT_CONNECTION_INIT) {
        if (connectionInterval != null) {
          window.clearInterval(connectionInterval);
          connectionInterval = null;
        }
        connectionInterval = window.setInterval(() => {
          window.parent.postMessage(
            makeswiftConnectionCheck({ currentUrl: window.location.href }),
            { targetOrigin: appOrigin }
          );
        }, CONNECTION_PING_INTERVAL_MS);
      }
    }
  }, [appOrigin]);
}
export {
  useBuilderConnectionPing
};
//# sourceMappingURL=use-builder-connection-ping.js.map