import { observeAttributes } from '../helpers/componentHelpers';

const booleanAttributesList = [
  'readonly',
  'focused',
  'invalid',
  'has-label',
  'required',
  'disabled',
  'checked',
  'has-helper',
  'has-value',
  'step-buttons-visible',
  'hover',
  'has-error-message',
  'focus-ring',
  'opened',
  'active',
  'password-visible',
  'opening',
  'closing',
  'has-no-options',
  'loading',
  'allow-custom-value',
  'loading',
];

const isBooleanAttribute = (attr) => booleanAttributesList.includes(attr);
// we want all the valueless attributes to have "true" value
// and all the falsy attribute to be removed
export const normalizeBooleanAttributesMixin = (superclass) =>
  class NormalizeBooleanAttributesMixinClass extends superclass {
    init() {
      super.init?.();

      observeAttributes(
        this,
        (attrs) =>
          attrs.forEach((attr) => {
            const attrVal = this.getAttribute(attr);

            if (isBooleanAttribute(attr)) {
              if (attrVal === '') {
                this.setAttribute(attr, 'true');
              } else if (attrVal === 'false') {
                this.removeAttribute(attr);
              }
            } else if (!attrVal) {
              // eslint-disable-next-line no-console
              console.debug(
                `attribute "${attr}" has no value, should it be added to the boolean attributes list?`
              );
            }
          }),
        {}
      );
    }
  };
