import {
  addOverlay,
  getFileByName,
  getMarkdownContentByName,
} from '@/editor/indexeddb/operations'
import { ALL_OPERATORS } from '@/editor/utils'
import type { ContentYaml, MappedMilestone, OverlayYaml } from '../types'

export const getContentFile = async (content?: ContentYaml) => {
  const fileName = content?.file_name
  return fileName ? await getFileByName(fileName) : undefined
}

export const getContentText = async (content?: ContentYaml) => {
  const contentFileName = content?.content_path
  if (!contentFileName) return content?.content

  const contentEntry = await getMarkdownContentByName(contentFileName)
  return contentEntry?.content
}

export const loadOverlay = async (
  injectInfoId: number,
  overlay?: OverlayYaml
) => {
  if (overlay) {
    await addOverlay({ ...overlay, injectInfoId })
  }
}

export const getMilestoneCondition = (
  condition: string,
  milestonesWithIds: MappedMilestone[]
) =>
  condition
    .match(/\bnot\b|\band\b|\bor\b|[a-zA-Z0-9_]+|[()]/g)
    ?.map(
      value =>
        Number(
          ALL_OPERATORS.find(operator => operator.label === value)?.value
        ) || milestonesWithIds.find(milestone => milestone.name === value)?.id
    )
    .filter(id => id !== undefined) as number[]
