import { warning } from "../../../dev-warning";

const expiringAnnounce = (announce) => {
  let wasCalled = false;
  let isExpired = false;

  // not allowing async announcements
  const timeoutId = setTimeout(() => {
    isExpired = true;
  });
  const result = (message) => {
    if (wasCalled) {
      warning("Announcement already made. Not making a second announcement");
      return;
    }
    if (isExpired) {
      warning(`
        Announcements cannot be made asynchronously.
        Default message has already been announced.
      `);
      return;
    }
    wasCalled = true;
    announce(message);
    clearTimeout(timeoutId);
  };

  // getter for isExpired
  // using this technique so that a consumer cannot
  // set the isExpired or wasCalled flags
  result.wasCalled = () => wasCalled;
  return result;
};

export default expiringAnnounce;
