/**
 * Applies attributes to user popouts.
 * @module User
 * @memberof Builtin.Attributes.Components.Popouts
 */

import { patch, unpatch } from '@vizality/patcher';
import { getModule } from '@vizality/webpack';

export const labels = [ 'Components', 'Popouts', 'User' ];

export default builtin => {
  const UserPopout = getModule(m => m?.type?.displayName === 'UserPopoutContainer');
  patch('vz-attributes-popout-user', UserPopout, 'type', (_, res) => {
    try {
      res.props.setPopoutRef = elem => {
        if (elem) {
          elem.setAttribute('vz-user-id', res?.props?.user?.id);
          elem.parentElement.setAttribute('vz-popout', 'user');
        }
      };
    } catch (err) {
      return builtin.error(builtin._labels.concat(labels), err);
    }
  });

  /**
   * Fixes user popouts causing the app to sometimes shift up.
   * @see {@link https://github.com/lavasquid-vizality/fix-popout}
   * @author LavaSquid
   * @license MIT
   */
  const { layer } = getModule(m => m.layer && m.layerContainer);
  const ReferencePositionLayer = getModule(m => m.displayName === 'ReferencePositionLayer');
  patch('vz-attributes-popout-user-fix', ReferencePositionLayer.prototype, 'render', (_, res, _this) => {
    if (res.props.className !== layer) {
      return;
    }

    if (_this.elementRef.current) {
      res.props.style = {
        ...res.props.style,
        ..._this.calculateState().style
      };
    }
  });

  return () => {
    unpatch('vz-attributes-popout-user');
    unpatch('vz-attributes-popout-user-fix');
  };
};
