import { CoreSrcSet } from 'twitch-core-ui/src/components/core-image/component';

interface SrcAndSrcSet {
  src: string;
  srcSet: CoreSrcSet;
}

export function buildStringFromTemplate(
  template: string,
  width: number,
  height: number,
): string {
  return template
    .replace(/{width}/g, width.toString())
    .replace(/{height}/g, height.toString());
}

/**
 * The very first item must be the default item
 *
 * When modifying these options please try to not switch to any size that
 * would cause a common phone to download new assets when moving between
 * landscape and portrait.
 **/
export const DEFAULT_BOX_ART_WIDTH = 136;
export const BOX_ART_ASPECT_RATIO = 4 / 3;
export const DEFAULT_BOX_ART_HEIGHT =
  DEFAULT_BOX_ART_WIDTH * BOX_ART_ASPECT_RATIO;
const BOXART_IMAGE_WIDTHS = [DEFAULT_BOX_ART_WIDTH, 52, 272, 429, 650];

export const DEFAULT_THUMBNAIL_WIDTH = 320;
export const THUMBNAIL_ASPECT_RATIO = 9 / 16;
export const DEFAULT_THUMBNAIL_HEIGHT =
  DEFAULT_BOX_ART_WIDTH * THUMBNAIL_ASPECT_RATIO;
const THUMBNAIL_IMAGE_WIDTHS = [DEFAULT_THUMBNAIL_WIDTH, 80, 400, 600, 1280];

export function getSrcAndSrcSet(
  imageTemplate: string,
  imageWidths: number[],
  aspectRatio: number,
): SrcAndSrcSet {
  return imageWidths.reduce(
    (prev, imageWidth, index) => {
      const image = buildStringFromTemplate(
        imageTemplate,
        imageWidth,
        Math.round(imageWidth * aspectRatio),
      );
      const key = `${imageWidth}w`;

      return {
        src: index === 0 ? image : prev.src,
        srcSet: {
          ...prev.srcSet,
          [key]: image,
        },
      };
    },
    {} as SrcAndSrcSet,
  );
}

export function getBoxArtSrcAndSrcSet(imageTemplate: string): SrcAndSrcSet {
  return getSrcAndSrcSet(
    imageTemplate,
    BOXART_IMAGE_WIDTHS,
    BOX_ART_ASPECT_RATIO,
  );
}

export function getChannelThumbnailSrcAndSrcSet(
  imageTemplate: string,
): SrcAndSrcSet {
  return getSrcAndSrcSet(
    imageTemplate,
    THUMBNAIL_IMAGE_WIDTHS,
    THUMBNAIL_ASPECT_RATIO,
  );
}
