import { forceUpdateElement } from '@vizality/util/react';
import { patch, unpatch } from '@vizality/patcher';
import { getModule } from '@vizality/webpack';
import React from 'react';

export const labels = [ 'Components', 'Avatar' ];

/**
 * Applies attributes to user avatars.
 * @module Avatar
 * @memberof Builtin.Attributes.Components
 */
export default builtin => {
  const AvatarModule = getModule('AnimatedAvatar');
  const Avatar = AvatarModule?.default;
  patch('vz-attributes-avatars', AvatarModule, 'default', (args, res) => {
    try {
      const avatar = args[0]?.src;
      if (avatar?.includes('/avatars')) {
        [ , res.props['vz-user-id'] ] = avatar.match(/\/(?:avatars|users)\/(\d+)/);
      }
    } catch (err) {
      return builtin.error(builtin._labels.concat(labels), err);
    }
  });

  /**
   * Re-render avatars using the patched component.
   */
  patch('vz-attributes-animated-avatars', AvatarModule?.AnimatedAvatar, 'type', (_, res) => {
    try {
      return <Avatar {...res.props} />;
    } catch (err) {
      return builtin.error(builtin._labels.concat(labels), err);
    }
  });

  setImmediate(() => forceUpdateElement(`.${getModule('wrapper', 'avatar')?.wrapper?.split(' ')[0]}`, true));
  setImmediate(() => forceUpdateElement(`.${getModule('avatar', 'timestamp', 'messageContent')?.avatar?.split(' ')[0]}`, true));

  return () => {
    unpatch('vz-attributes-avatars');
    unpatch('vz-attributes-animated-avatars');
  };
};
