import { createDispatchEvent } from '../helpers/mixinsHelpers';

export const lifecycleEventsMixin = (superclass) =>
  class LifecycleEventsMixinClass extends superclass {
    #dispatchConnected = createDispatchEvent.bind(this, 'connected');

    #dispatchDisconnected = createDispatchEvent.bind(this, 'disconnected');

    connectedCallback() {
      if (this.rootElement.isConnected) {
        super.connectedCallback?.();

        // we are waiting for all components to listen before dispatching
        setTimeout(this.#dispatchConnected);
      }
    }

    disconnectedCallback() {
      super.disconnectedCallback?.();

      this.#dispatchDisconnected();
    }
  };
