import EventEmitter from "../tools/event-emitter";

const SHOW_EVENT = "show";
const HIDE_EVENT = "hide";

function ModalHandler() {
  let _ref;
  let _modalRef;
  let _modalId;
  let eventEmitter = new EventEmitter();

  function setRef(ref) {
    _ref = ref;
    _modalRef = new bootstrap.Modal(ref);
    _ref.addEventListener('hidden.bs.modal', () => {
      eventEmitter.dispatchEvent(HIDE_EVENT);
    });
    _ref.addEventListener('show.bs.modal', () => {
      eventEmitter.dispatchEvent(SHOW_EVENT);
    });
  }

  function show() {
    _modalRef.show();
  }

  function hide() {
    _modalRef.hide();
  }

  function setModalId(modalId) {
    _modalId = modalId;
  }
  
  function onHidden(callback) {
    eventEmitter.on(HIDE_EVENT, callback);
  }
  
  function onShow(callback) {
    eventEmitter.on(SHOW_EVENT, callback);
  }

  return {
    setRef,
    show,
    hide,
    setModalId,
    onHidden,
    onShow,
  };
}

export default ModalHandler;
