import React from "react";

export interface SrcProps {
  src: string;
  width?: number;
  height?: number;
}

export interface PlaceholderProps {
  height: number;
  width: number;
}

export type Props = SrcProps | PlaceholderProps;

/**
 * A responsive image (or placeholder).
 *
 * Renders a single `<img />` tag with responsive styles applied. When `src` is
 * not provided, a placeholder image of the correct size is rendered.
 */
export class ResponsiveImage extends React.Component<Props> {
  public render() {
    const { props } = this;
    const src = "src" in props ? props.src : emptySvgUri(props.width, props.height);
    return <img src={src} width={props.width} height={props.height} style={{ maxWidth: "100%", height: "auto" }} />;
  }
}

/**
 * Creates an SVG string with a specific width/height.
 */
const emptySvgUri = (width: number, height: number) =>
  `data:image/svg+xml;utf8,<svg width="${width}px" height="${height}px" version="1.1" xmlns="http://www.w3.org/2000/svg"></svg>`;
