import {
  addLearningActivity,
  addLearningObjective,
} from '@/editor/indexeddb/operations'
import type { LearningActivityInfo } from '@/editor/indexeddb/types'
import { LearningActivityType } from '@/editor/indexeddb/types'
import type {
  LearningActivityYaml,
  LearningActivityYamlWithType,
  LearningObjectiveYaml,
  LearningObjectiveYamlWithTypes,
  MappedActivity,
  MilestoneYaml,
} from '../types'

export const getActivityType = (
  activity: LearningActivityYaml,
  toolMilestones: MilestoneYaml[],
  emailMilestones: MilestoneYaml[]
) => {
  if (
    emailMilestones.find(
      (milestone: MilestoneYaml) => milestone.name === activity.name
    )
  ) {
    return LearningActivityType.EMAIL
  }
  if (
    toolMilestones.find(
      (milestone: MilestoneYaml) => milestone.name === activity.name
    )
  ) {
    return LearningActivityType.TOOL
  }
  // TODO no demonstration
  return LearningActivityType.TOOL
}

export const addTypesToActivities = (
  objectives: LearningObjectiveYaml[],
  toolMilestones: MilestoneYaml[],
  emailMilestones: MilestoneYaml[]
) =>
  objectives.map((objective: LearningObjectiveYaml) => ({
    ...objective,
    activities: objective.activities.map(activity => ({
      ...activity,
      type: getActivityType(activity, toolMilestones, emailMilestones),
    })),
  }))

export const addActivityIdsToActivityMilestones = (
  activityMilestones: MilestoneYaml[],
  activities: LearningActivityInfo[]
): (MappedActivity | undefined)[] =>
  activityMilestones.map((milestone: MilestoneYaml) => {
    if (milestone.activity) {
      const activity = activities.find(a => a.name === milestone.activity)
      if (activity) {
        return {
          id: activity.id,
          milestoneName: milestone.name,
        }
      }
    }
  })

const loadActivities = async (
  activities: LearningActivityYamlWithType[],
  objectiveId: number
) =>
  Promise.all(
    activities.map(async activity => {
      const newActivity = {
        name: activity.name,
        type: activity.type,
        learningObjectiveId: objectiveId,
      }
      const id = await addLearningActivity(newActivity)
      return { id, ...newActivity }
    })
  )

export const loadObjectives = async (
  objectives: LearningObjectiveYamlWithTypes[]
) =>
  Promise.all(
    objectives.map(async objective => {
      const id = await addLearningObjective({ name: objective.name })
      return await loadActivities(objective.activities, id)
    })
  )
