import * as React from 'react';

import { withLatencyTracker } from 'mweb/common/latency/withLatencyTracker';

export type LatencyTrackedImageProps = React.DetailedHTMLProps<
  React.ImgHTMLAttributes<HTMLImageElement>,
  HTMLImageElement
>;

export class LatencyTrackedImage extends React.Component<
  LatencyTrackedImageProps,
  {}
> {
  static displayName: string = 'LatencyTrackedImage';
  latencyName: string | undefined;
  latencyEventName: string = 'load';
  latencyEventTarget: HTMLImageElement;

  constructor(props: LatencyTrackedImageProps) {
    super(props);
    this.latencyName = props.alt
      ? `${props.alt.replace(/\W/g, '')}_Image`
      : undefined;
  }

  render(): JSX.Element {
    return (
      <img
        {...this.props}
        ref={c => (this.latencyEventTarget = c as HTMLImageElement)}
      />
    );
  }
}

export default withLatencyTracker(LatencyTrackedImage);
