import {
  addInjectControl,
  addInjectInfo,
  addQuestionnaire,
  addQuestionnaireQuestion,
  getMilestoneByTypeAndReferenceId,
} from '@/editor/indexeddb/operations'
import { InjectType, MilestoneEventType } from '@/editor/indexeddb/types'
import type {
  MappedMilestone,
  MappedQuestionnaireControl,
  QuestionYaml,
  QuestionnaireYaml,
} from '../types'
import { extractFirstMilestone } from './milestones'
import { getContentText, getMilestoneCondition, loadOverlay } from './shared'

const loadQuestions = async (
  questions: QuestionYaml[],
  questionnaireId: number
) => {
  questions.map(async question => {
    const content = await getContentText(question.content)

    await addQuestionnaireQuestion({
      questionnaireId,
      text: content || '',
      max: question.max,
      correct: question.correct,
      labels: question.labels,
    })
  })
}

export const loadQuestionnaires = async (questionnaires: QuestionnaireYaml[]) =>
  await Promise.all(
    questionnaires.map(async questionnaire => {
      const injectInfoId = await addInjectInfo({
        name: questionnaire.title,
        type: InjectType.QUESTIONNAIRE,
      })
      const id = await addQuestionnaire({
        injectInfoId: injectInfoId,
        title: questionnaire.title,
      })
      await loadOverlay(injectInfoId, questionnaire.overlay)
      await loadQuestions(questionnaire.questions, id)
      const milestone = await getMilestoneByTypeAndReferenceId(
        MilestoneEventType.INJECT,
        injectInfoId
      )

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

export const loadQuestionnaireControls = (
  questionnaireControls: MappedQuestionnaireControl[],
  milestonesWithIds: MappedMilestone[]
) => {
  questionnaireControls.forEach(async control => {
    await addInjectControl({
      injectInfoId: control.id,
      start: control.time,
      milestoneCondition: control.milestoneCondition
        ? getMilestoneCondition(control.milestoneCondition, milestonesWithIds)
        : [],
    })
  })
}
