/**
 * Program: validation directive
 * Author: SDL
 * Description: validation directive
 */
/* eslint-disable prefer-destructuring */
/* eslint-disable no-unused-vars */
import SDLUtil from '@/utils/SDLUtil';

const showErrMsg = (field, msg) => {
  const errDiv = document.createElement('div');

  errDiv.innerHTML = SDLUtil.getMsgProp(msg);
  errDiv.className = 'invalid-feedback';
  field.classList.add('is-invalid');
  field.insertAdjacentElement('afterend', errDiv);
};
const validationObj = (field, valids) => {
  Array.from(field.parentElement.querySelectorAll('.invalid-feedback')).forEach(el => {
    try {
      el.remove();
    } catch (e) {
      el.parentNode.removeChild(el);
    }
  });

  if (field.willValidate && !field.checkValidity()) {
    let errMsg = field.validationMessage;
    if (field.getAttribute('errorMessage')) errMsg = field.getAttribute('errorMessage');

    showErrMsg(field, errMsg);
  } else if (valids.length > 0) {
    for (let i = 0; i < valids.length; i += 1) {
      if (!valids[i].validFuncs()) {
        showErrMsg(field, valids[i].errorMessage);
        break;
      }
    }
  }
};

export default {
  beforeMount(el, binding) {
    let groupId = '';
    let valids = [];
    if (binding.value && Object.prototype.hasOwnProperty.call(binding.value, 'groupId')) {
      groupId = binding.value.groupId;
    }
    if (binding.value && Object.prototype.hasOwnProperty.call(binding.value, 'valids')) {
      valids = binding.value.valids;
    }
    SDLUtil.setValidList({ el, groupId });

    el.setAttribute('required', 'required');
    el.addEventListener('blur', e => {
      e.preventDefault();

      Array.from(document.querySelectorAll('.is-invalid')).forEach(ele => ele.classList.remove('is-invalid'));
      validationObj(el, valids);
    });
    el.addEventListener('focus', e => {
      e.preventDefault();

      el.classList.remove('is-invalid');
    });
  },
  unmounted(el, binding) {
    let groupId = '';
    if (binding.value && Object.prototype.hasOwnProperty.call(binding.value, 'groupId')) {
      groupId = binding.value.groupId;
    }
    SDLUtil.deleteValidList(el, groupId);
  },
};
