import {
  DOWNLOAD_ITEM_IDS,
  MarkdownIcon,
  buildPngDownloadItem,
  toCsvString,
  triggerLinkDownload,
  type DownloadItem,
} from '../actions/download'
import type { MarkdownWidgetData } from './types'

/**
 * Download menu items for the Markdown widget. Always includes a `.md`
 * item that saves the markdown source verbatim. When `getCaptureEl` is
 * supplied, prepends a PNG item that rasterises the captured element via
 * `html2canvas`.
 */
export function createMarkdownDownloadConfig(args: {
  filename: string
  getData: () => MarkdownWidgetData
  getCaptureEl?: () => HTMLElement | null
  pngPixelRatio?: number
  pngBackgroundColor?: string | null
}): DownloadItem[] {
  const items: DownloadItem[] = []
  if (args.getCaptureEl) {
    items.push(
      buildPngDownloadItem({
        filename: args.filename,
        getCaptureEl: args.getCaptureEl,
        pixelRatio: args.pngPixelRatio,
        backgroundColor: args.pngBackgroundColor,
      }),
    )
  }
  items.push({
    id: DOWNLOAD_ITEM_IDS.markdown,
    label: 'Markdown',
    icon: <MarkdownIcon fontSize='small' />,
    resolve: () => {
      const data = args.getData()
      const blob = new Blob([data.content ?? ''], {
        type: 'text/markdown;charset=utf-8;',
      })
      const url = URL.createObjectURL(blob)
      return Promise.resolve({
        url,
        filename: `${args.filename}.md`,
        revoke: () => URL.revokeObjectURL(url),
      })
    },
  })
  return items
}

// Re-export pure helpers consumers may want when building a custom Download item.
export { toCsvString, triggerLinkDownload }
