import {
  addTool,
  addToolResponse,
  getMilestoneByTypeAndReferenceId,
  updateToolResponseMilestoneCondition,
} from '@/editor/indexeddb/operations'
import { MilestoneEventType } from '@/editor/indexeddb/types'
import type {
  MappedActivity,
  MappedMilestone,
  MappedToolResponseControl,
  ToolResponseYaml,
  ToolYaml,
} from '../types'
import { extractFirstMilestone } from './milestones'
import { getContentFile, getContentText, getMilestoneCondition } from './shared'

const loadToolResponses = async (
  toolId: number,
  responses: ToolResponseYaml[],
  activityMilestones: MappedActivity[]
) =>
  await Promise.all(
    responses.map(async response => {
      const file = await getContentFile(response.content)
      const content = await getContentText(response.content)
      const learningActivityId = activityMilestones.find(
        activity =>
          extractFirstMilestone(response.control?.activate_milestone) ===
          activity.milestoneName
      )?.id

      const id = await addToolResponse({
        toolId,
        learningActivityId,
        parameter: response.param,
        isRegex: response.regex,
        content,
        fileId: file?.id,
        time: response.time,
      })
      const milestone = learningActivityId
        ? await getMilestoneByTypeAndReferenceId(
            MilestoneEventType.LEARNING_ACTIVITY,
            learningActivityId
          )
        : await getMilestoneByTypeAndReferenceId(MilestoneEventType.TOOL, id)

      return {
        id,
        milestoneId: milestone?.id,
        milestoneName: extractFirstMilestone(
          response.control?.activate_milestone
        ),
        milestoneCondition: response.control?.milestone_condition,
      }
    })
  )

export const loadTools = async (
  activityMilestones: MappedActivity[],
  tools: ToolYaml[]
) =>
  await Promise.all(
    tools.map(async tool => {
      const id = await addTool({
        name: tool.name,
        tooltipDescription: tool.tooltip_description,
        defaultResponse: tool.default_response,
        hint: tool.hint,
      })
      return await loadToolResponses(id, tool.responses, activityMilestones)
    })
  )

export const loadToolResponseControls = (
  toolControls: MappedToolResponseControl[],
  milestonesWithIds: MappedMilestone[]
) => {
  toolControls.forEach(
    async control =>
      control.milestoneCondition &&
      (await updateToolResponseMilestoneCondition(
        control.id,
        getMilestoneCondition(control.milestoneCondition, milestonesWithIds)
      ))
  )
}
