const passwordDraggableMixin = (superclass) =>
  class PasswordDraggableMixinClass extends superclass {
    get isReadOnly() {
      return this.hasAttribute('readonly') && this.getAttribute('readonly') !== 'false';
    }

    init() {
      // there is an issue in Chrome that input field with type password cannot be D&D
      // so in case the input is draggable & readonly, we are changing the input type to "text" before dragging
      // and return the original type when done
      super.init?.();

      const ele = this.querySelector('input');

      ele?.addEventListener('mousedown', (e) => {
        if (this.isDraggable && this.isReadOnly) {
          ele.setAttribute('inert', 'true');

          const inputEle = e.target;
          const prevType = inputEle.getAttribute('type');
          inputEle.setAttribute('type', 'text');
          setTimeout(() => {
            inputEle.focus();
          });

          const onComplete = (_) => {
            inputEle.setAttribute('type', prevType);
            ele.removeAttribute('inert');
            this.removeEventListener('mouseup', onComplete);
            this.removeEventListener('dragend', onComplete);
          };

          this.addEventListener('dragend', onComplete, { once: true });
          this.addEventListener('mouseup', onComplete, { once: true });
        }
      });
    }
  };

export default passwordDraggableMixin;
