import {Module} from "@/interfaces";
import {Exercise} from "@/interfaces/exam";
import {Stat} from "@/interfaces/user";
import {uniq} from "lodash";
import {groupBySession} from "./stats";

export const MODULE_ARRAY: Module[] = ["reading", "listening", "writing", "speaking", "level"];

export const moduleLabels: {[key in Module]: string} = {
	listening: "Listening",
	reading: "Reading",
	speaking: "Speaking",
	writing: "Writing",
	level: "Level",
};

export const sortByModule = (a: {module: Module; [key: string]: any}, b: {module: Module; [key: string]: any}) => {
	return MODULE_ARRAY.findIndex((x) => a.module === x) - MODULE_ARRAY.findIndex((x) => b.module === x);
};

export const sortByModuleName = (a: string, b: string) => {
	return MODULE_ARRAY.findIndex((x) => a === x) - MODULE_ARRAY.findIndex((x) => b === x);
};

export const countExercises = (exercises: Exercise[]) => {
	const lengthMap = exercises.map((e) => {
		if (e.type === "multipleChoice") return e.questions.length;
		if (e.type === "interactiveSpeaking") return e.prompts.length;
		if (e.type === "fillBlanks") return e.words.length;
		if (e.type === "writeBlanks") return e.solutions.length;
		if (e.type === "matchSentences") return e.sentences.length;
		if (e.type === "trueFalse") return e.questions.length;
		return 1;
	});

	return lengthMap.reduce((accumulator, current) => accumulator + current, 0);
};

export const countFullExams = (stats: Stat[]) => {
	const sessionExams = groupBySession(stats);
	return Object.keys(sessionExams).filter((x) => {
		const sessionStats = sessionExams[x as keyof typeof sessionExams];
		const sessionModules = sessionStats.map((x) => x.module);

		return (
			sessionModules.includes("reading") &&
			sessionModules.includes("listening") &&
			sessionModules.includes("writing") &&
			sessionModules.includes("speaking")
		);
	}).length;
};

export const countExamModules = (stats: Stat[]) => {
	const sessionExams = groupBySession(stats);
	const modulesPerSession = Object.keys(sessionExams).map((x) => {
		const sessionStats = sessionExams[x as keyof typeof sessionExams];
		const sessionModules = uniq(sessionStats.map((x) => x.module));

		return sessionModules.length;
	});

	return modulesPerSession.reduce((acc, curr) => curr + acc, 0);
};
