/**
 * @description
 * Ouvre une modal de confirmation d'action
 *
 * @param {string} [selector=*[data-requires-confirmation]]
 * @param {function} [callback=()=>{}]
 */
const SyliusConfirmation = (selector = '*[data-requires-confirmation]', callback = () => {}) => {
  Array.from(document.querySelectorAll(selector))
    .forEach((el) => {
      el.addEventListener('click', (e) => {
        e.preventDefault();
        $('#confirmation-modal')
          .on('shown.bs.modal', ({ target }) => {
            const button = target.querySelector('button[type="submit"]');
            if (button) {
              button.addEventListener('click', () => {
                if (el.form) {
                  el.form.submit();
                } else if (el.href) {
                  window.location = el.href;
                }

                callback(target);
              });
            }
          })
          .modal();
      });
    });
};

export default SyliusConfirmation;
