import {
  buildCsvDownloadItem,
  buildPngDownloadItem,
  type DownloadItem,
} from '../actions/download'
import type { BarWidgetData } from './types'

export interface BarDownloadConfigArgs {
  filename: string
  getData: () => BarWidgetData
  /**
   * Optional getter for the widget's capture element (registered by
   * `Widget.State` on its success path). When provided, a PNG item is
   * prepended to the returned list. Wire it to
   * `() => getCaptureEl(id)`.
   */
  getCaptureEl?: () => HTMLElement | null
  /** PNG `pixelRatio` (default 2). */
  pngPixelRatio?: number
  /** PNG `backgroundColor` (default transparent). */
  pngBackgroundColor?: string | null
}

/**
 * Builds download items for the Bar widget. Always includes a CSV item
 * with one `name,value` block per series, separated by an empty row when
 * there are multiple. When `getCaptureEl` is supplied, also prepends a PNG
 * item that rasterises the captured element via `html2canvas`.
 */
export function createBarDownloadConfig(
  args: BarDownloadConfigArgs,
): DownloadItem[] {
  const items: DownloadItem[] = []
  if (args.getCaptureEl) {
    items.push(
      buildPngDownloadItem({
        filename: args.filename,
        getCaptureEl: args.getCaptureEl,
        pixelRatio: args.pngPixelRatio,
        backgroundColor: args.pngBackgroundColor,
      }),
    )
  }
  items.push(
    buildCsvDownloadItem({
      filename: args.filename,
      getRows: () => {
        const data = args.getData()
        const rows: unknown[][] = []
        for (const [i, series] of data.entries()) {
          if (i > 0) rows.push([])
          rows.push(['name', 'value'])
          for (const d of series) rows.push([d.name, d.value])
        }
        return rows
      },
    }),
  )
  return items
}
