import * as React from 'react';
import { CardImage } from 'twitch-core-ui';
import { CardImageProps } from 'twitch-core-ui/src/components/card/card-image/component';
import { withLatencyTracker } from 'mweb/common/latency/withLatencyTracker';

if (process.env.BROWSER) {
  require('./cardImageWrapper.sass');
}

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

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

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

export interface CardImageWrapperProps
  extends ObjectOmit<CardImageProps, 'refHandler'> {
  latencyTracked: boolean;
}

export class CardImageWrapper extends React.Component<
  CardImageWrapperProps,
  {}
> {
  render(): JSX.Element {
    const Image = this.props.latencyTracked
      ? withLatencyTracker(LatencyTrackedCardImage)
      : CardImage;
    return (
      <div className="card-image-wrapper">
        <Image {...this.props} />
      </div>
    );
  }
}
