import { isUndefined } from '@transferwise/neptune-validation';
import { useEffect } from 'react';

import { ParentElement } from '../..';

type Data = {
  attachListener: boolean;
  callback: EventListenerOrEventListenerObject;
  eventType: string;
  parent: ParentElement | undefined;
};

export const useConditionalListener = ({ attachListener, callback, eventType, parent }: Data) => {
  useEffect(() => {
    if (attachListener && !isUndefined(parent)) {
      parent.addEventListener(eventType, callback, true);
    }

    return () => {
      if (!isUndefined(parent)) {
        parent.removeEventListener(eventType, callback, true);
      }
    };
  }, [attachListener, callback, eventType, parent]);
};
