import { cdnUrl } from '../core'
import { IconDefinition, iconsCache } from '../icons'
import { GetIconDetailsResult, IconProp } from './icon.types'

/**
 * Returns an object with either 'src' or 'customIcon', depending on whether the provided icon is:
 * - not in library:    'src' as CDN url
 * - in library:            'customIcon' as icon definition object
 */
export function getIconDetails(icon?: IconProp): GetIconDetailsResult {
  if (!icon) return {}

  // Compute CDN url if icon is not in library cache
  if (!iconsCache.has(icon)) {
    const prefix = icon.slice(0, 3)

    return {
      src: `${cdnUrl}/common/icons/ui/${prefix}/${icon}.svg`,
    }
  }

  // Compute relevant properties based on icon definition from the library
  const { details, name, pathProps = [], svgProps = {} } = iconsCache.get(icon) as IconDefinition
  const [width, height, , , d] = details
  const viewBox = `0 0 ${width} ${height}`

  const customIcon = {
    d: Array.isArray(d) ? d : [d],
    pathProps: Array.isArray(pathProps) ? pathProps : [pathProps],
    svgProps: { 'data-name': name, viewBox, ...svgProps },
  }

  return {
    customIcon,
  }
}
