File

src/app/models/journey.ts

import { ProposedActivity, Status } from "./proposed-activity";
import { LmsService } from "../services/lms.service";
import { environment } from "src/environments/environment";
import { CabriDataService } from "../services/cabri-data.service";
import { LrsUtils } from "./lrs/lrsUtils";
import { CabriActivity } from "./cabri-activity";

export enum JourneyMode {
	bilan = "Bilan",
	entraînement = "Entraînement",
	entrainement = "Entrainement",
	remediation = "Remédiation"
}

export enum journeyStatus {
	// index 1
	inProgress = "Les parcours en cours",
	// index 2
	toDo = "Mes parcours à faire",
	// index 3
	completed = "Les parcours terminés",
	// index 4
	offlineJourneysByAssignation = "Mes parcours",
	// index 5
	allJourneys = "Tous les parcours"
}

export class JourneysByStatus {
	[status: string]: { opened: boolean; items: Journey[] };
}

export enum JourneyDiagnosticAward {
	maxAward = 5,
	maxTotalAwards = 10
}
/**
 * model for api.mathia recommendation
 */
export class JourneyRecommendation {
	journey: number;
	journeyDifficulty: JourneyMode;
	journeyTitle: string;
	student: string;
	recoType?: string;
	skill?: string;
	confidence?: number;
	erreur_type?: number;
}

export class Journey {
	id: number;
	idSession?: string;
	assignationId: number;
	kidaia = false;
	level: any;
	parcoursId: number;
	title: string;
	type: string;
	difficulty: Array<{ id: string; label: string }> | string;
	bilan = false;
	isAdventureBilan = false;
	recommandation = false;
	remediation = false;
	completed: boolean;
	exercises: ProposedActivity[];
	nextActivityProposed: ProposedActivity;
	firstActivityDone = false;
	resume: boolean;
	reload = false;
	start: boolean;
	allAskedQuestions: Array<any>;
	next = false;
	farthest = false;
	assignation = false;
	correctAnswers?: number;
	content: {
		source: object;
		difficulty: Array<any>;
		exercises: Array<any>;
		educationalLevel: { id: string; label: string }[];
		id: number;
		title: string;
	};
	learner: { uid: number };
	model: boolean;
	uid: string | number;
	duration = 0;
	dates;
	journeyStatus: string | number;
	educationalLevel: Array<{ id: string; label: string }>;
	// id Session from lrs
	_id?: string;
	public environment: { production: boolean; activityVersion: number; kidaia: boolean };

	cabriService: CabriDataService;
	lmsService: LmsService;
	isCompetition = false;
	selected?: boolean;
	selectedActivity: CabriActivity;
	diagnostic: any;
	originalAllJourneysByStatus: any;
	private _activityContainTrainingMod: any;

	private get globalService() {
		return this.cabriService.globalService;
	}
	private get router() {
		return this.cabriService.router;
	}
	private get audioService() {
		return this.cabriService.accountService.audioService;
	}
	private get accountService() {
		return this.cabriService.accountService;
	}

	private get lrsService() {
		return this.cabriService.lrs;
	}
	private get networkService(){
		return this.accountService.networkService
	}
	constructor(
		cabriService: CabriDataService,
		lmsService: LmsService,
		id: number,
		educationalLevel: Array<{ id: string; label: string }>,
		assignationId: number | null,
		title: string,
		difficulty: Array<{ id: string; label: string }> | string,
		resume: boolean,
		assignation: boolean,
		exercises?: ProposedActivity[],
		allAskedQuestions?: Array<any>
	) {
		this.id = id;
		this.cabriService = cabriService;
		this.lmsService = lmsService;
		this.environment = environment;

		if (assignationId) {
			this.assignationId = assignationId;
		}
		this.title = title;

		if (educationalLevel && Array.isArray(educationalLevel) && educationalLevel.length > 0) {
			this.level = educationalLevel[0].label;
		} else if (educationalLevel) {
			this.level = educationalLevel;
		}

		this.assignation = assignation;
		this.difficulty = difficulty;
		if (this.difficulty && typeof this.difficulty === "string") {
			if (
				this.difficulty === JourneyMode.remediation ||
				this.difficulty === JourneyMode.entraînement ||
				this.difficulty === JourneyMode.entrainement
			) {
				this.bilan = false;
			} else {
				this.bilan = true;
				this.isAdventureBilan = this.title.toLowerCase().startsWith("da");
			}
		}
		if (this.difficulty && Array.isArray(this.difficulty) && this.difficulty.length > 0) {
			if (
				this.difficulty[0].label === JourneyMode.remediation ||
				this.difficulty[0].label === JourneyMode.entraînement ||
				this.difficulty[0].label === JourneyMode.entrainement
			) {
				this.bilan = false;
			} else {
				this.bilan = true;
			}
		}

		if (!this.completed) {
			this.completed = false;
		}
		this.exercises = new Array<ProposedActivity>();
		if (exercises) {
			this.exercises = exercises;
		}
		resume = false;
		if (resume) {
			this.resume = resume;
		}
		this.allAskedQuestions = new Array();
		if (this.allAskedQuestions.length > 0) {
			this.allAskedQuestions = allAskedQuestions;
		}
	}

	/**
	 * Construction of current journey in diagnostic mod
	 */

	getCurrentJourneyDiagnosticMod = () => {
		let currentUserJourney: Journey;
		let journey: Journey;
		if (this) {
			if (!this.environment.kidaia) {
				// mathia journey
				// select journey from user journey
				journey = this.lmsService.userJourneysByAssignation.find(j => {
					return j.id === this.id;
				});

				if (!journey) {
					// select journey from all journeys
					journey = this.lmsService.allJourneys.find(j => {
						return j.id === this.lmsService.userJourneyFromParams.id;
					});
				}
			} else {
				// kidaia journey
				journey = this.lmsService.userJourneyFromParams;
			}

			currentUserJourney = journey;
			currentUserJourney.start = true;
			if (currentUserJourney.idSession) {
				currentUserJourney.idSession = null;
			}
			currentUserJourney.exercises.forEach(data => {
				data.status = Status.notDone;
			});
			currentUserJourney.allAskedQuestions = new Array();
			return currentUserJourney;
		}
	};

	/**
	 * selection of journey exercise to be executed
	 */

	selectJourneyExercise = (exercises: ProposedActivity[], resume: boolean) => {
		let currentExercise: ProposedActivity;
		if (resume) {
			currentExercise = exercises.find(exercise => {
				return exercise.status === Status.notDone;
			});
			if (!currentExercise) {
				currentExercise = exercises.find(exercise => {
					return exercise.status === Status.done;
				});
			}
		} else {
			currentExercise = exercises[0];
		}

		return currentExercise;
	};

	getStartedCurrentJourneyTrainingMod = () => {
		let journey: Journey;
		if (!this.environment.kidaia) {
			journey = this.lmsService.userJourneysByAssignation.find(j => {
				return j.id === this.id;
			});
			if (!journey) {
				journey = this.lmsService.allJourneys.find(j => {
					return j.id === this.id;
				});
			}
		} else {
			journey = this.lmsService.userJourneyFromParams;
		}

		journey.completed = false;
		if (journey.idSession) {
			journey.idSession = null;
		}
		journey.start = true;
		journey.allAskedQuestions = new Array();
		journey.exercises.forEach((data: ProposedActivity) => {
			data.status = Status.notDone;
		});

		return journey;
	};

	/**
	 * get current journey when the journey is resumed in training mod
	 */

	getResumedCurrentJourneyTrainingMod = (journey: Journey): Promise<Journey> => {
		let currentUserJourney: Journey;
		return new Promise<Journey>(async (resolve, reject) => {
			// create copy in order to not modify original object
			const journeyCopy = this._journeyCopy(journey);
			// Reprendre un parcours
			let posInd = -1;
			let currentSessionAskedQuestions = new Array();
			if (this.resumeExerciseProcessing(journeyCopy)) {
				// Reprendre un parcours lorsqu'un exercice est en cours d'être joué
				const lastQuestion = journeyCopy.allAskedQuestions[journeyCopy.allAskedQuestions.length - 1];
				posInd = journeyCopy.exercises.findIndex(exercise => {
					return exercise.step === lastQuestion.step;
				});

				const idSession = lastQuestion.id_session;
				// garder le tableau avec le dernier id session stocké et éliminer tous les autres
				currentSessionAskedQuestions = journeyCopy.allAskedQuestions.filter(allAskedQuestions => {
					return allAskedQuestions.id_session === idSession;
				});
				if (posInd === -1) {
					// take first element of array if changes made to journey
					posInd = 0;
				}
			} else {
				// Reprendre un parcours lorsqu'un exercice a été terminé (Passage à l'exercice suivant)
				posInd = journeyCopy.exercises.findIndex(exercise => {
					return exercise.status === Status.notDone;
				});
				if (posInd === -1) {
					// take first element of array if changes made to journey
					posInd = 0;
				}

				currentSessionAskedQuestions = journeyCopy.allAskedQuestions.filter(allAskedQuestions => {
					return allAskedQuestions.step === journeyCopy.exercises[posInd].step;
				});
			}

			if (posInd > -1) {
				try {
					if (!this.cabriService.currentActivity) {
						await this.cabriService.setActivityId(journeyCopy.exercises[posInd].exerciseId);
					}
					let currJ: Journey;
					if (!this.environment.kidaia) {
						currJ = this.lmsService.userJourneysByAssignation.find(j => {
							return j.id === journeyCopy.id;
						});
						if (!currJ) {
							currJ = this.lmsService.allJourneys.find(j => {
								return j.id === journeyCopy.id;
							});
						}
					} else {
						currJ = this.lmsService.userJourneyFromParams;
					}

					currentUserJourney = journeyCopy;
					currentUserJourney.title = currJ.title;
					currentUserJourney.assignationId = currJ.assignationId;
					currentUserJourney.type = currJ.type;
					currentUserJourney.idSession = journeyCopy.idSession;
					currentUserJourney.resume = true;
					currentUserJourney.isCompetition = journeyCopy.isCompetition;
					if (currentSessionAskedQuestions && currentSessionAskedQuestions.length > 0) {
						// if there are more than one question asked during the session so connect it to journey property
						currentUserJourney.allAskedQuestions = currentSessionAskedQuestions;
						LrsUtils.idsession = currentUserJourney.allAskedQuestions[0].id_session;
					} else {
						// user is about to start new exercise among journey exercises so initilize an empty array
						currentUserJourney.allAskedQuestions = new Array();
					}
				} catch (err) {
					console.error("not exercise found", err);
					resolve(currentUserJourney);
				}
			}

			resolve(currentUserJourney);
		});
	};
	/**
	 * Copy journey object
	 */
	private _journeyCopy(journey: Journey) {
		const lmsService = journey.lmsService;
		const cabriService = journey.cabriService;
		journey.lmsService = journey.cabriService = null;
		const journeyCopy = JSON.parse(JSON.stringify(journey));
		journeyCopy.lmsService = lmsService;
		journeyCopy.cabriService = cabriService;
		return journeyCopy;
	}

	/**
	 * Resume an activity exercise when an exercise of journey is still playing
	 */
	resumeExerciseProcessing = (journey: Journey) => {
		return (
			journey.allAskedQuestions &&
			journey.allAskedQuestions.length > 0 &&
			journey.allAskedQuestions[journey.allAskedQuestions.length - 1].completed === 0
		);
	};

	/**
	 * Define journey selected Activity with the exercise that must be played
	 */
	defineJourneySelectedActivity = (journeyExercise: ProposedActivity) => {
		let selectedActivity: CabriActivity;
		selectedActivity = this.cabriService.activities.find(activity => {
			return Number(activity.id) === Number(journeyExercise.activityId);
		});

		const exercise = this.cabriService.exercices.getExercise(journeyExercise.exerciseId);

		if (selectedActivity) {
			selectedActivity.paramHidden("v-cursor-mod", { 3: false });
			this.cabriService.setSelectedActivity(selectedActivity);
			selectedActivity.params.forEach(param => {
				if (param.exercices) {
					param.defaultValue = exercise;
					param.value = exercise;
				}
			});
		}
		this.cabriService.defineExercice(selectedActivity);
		// define exercise default value
		if (exercise) {
			selectedActivity.setParamValue("ex", exercise);
		}

		return selectedActivity;
	};

	// Sécurité pour commencer le premier exercice du parcours en cas de parcours terminé
	selectDiagnosticAsSimpleExercise = async () => {
		return new Promise<void>(async resolve => {
			await this.cabriService.setActivityId(this.lmsService.currentUserJourney.exercises[0].exerciseId);
			resolve();
		});
	};

	/**
	 * Get next diagnostic activity if it's exist
	 */
	checkNextDiagnosticExercise = async (nextExercise: ProposedActivity) => {
		return new Promise(async (resolve, reject) => {
			if (!nextExercise) {
				reject(true);
				return;
			}

			if (!this.lmsService.currentUserJourney.exercises[nextExercise.step]) {
				reject(true);
				return;
			}
			try {
				// Prochain exercice
				await this.cabriService.setActivityId(this.lmsService.currentUserJourney.exercises[nextExercise.step].exerciseId);
				const exercise = this.cabriService.exercices.getExercise(
					this.lmsService.currentUserJourney.exercises[nextExercise.step].exerciseId
				);
				if (exercise && this.cabriService.currentActivity) {
					this.cabriService.currentActivity.setParamValue("ex", exercise);
				}

				// définir step (assignation + index) pour lrs
				resolve(true);
			} catch (err) {
				reject();
			}
		});
	};

	launchJourney = async (resume = false) => {
		this.lmsService.userJourneyFromParams = this;
		this.resume = resume;
		this.resume = resume;
		this.audioService.toggleMusicPlayback(false);
		this.audioService.playLaunchSound();
		if (this.lmsService.userJourneyFromParams && this.lmsService.userJourneyFromParams.bilan) {
			try {
				const diagnostic: any = await this.checkDiagnosticAvailability();
				if (diagnostic && !diagnostic.hasNextActivity) {
					if (!diagnostic.mastered) {
						return;
					}
					this.diagnostic = diagnostic;
					this.cabriService.setSelectedActivity(this.selectedActivity);
					LrsUtils.currentUser = this.accountService.team[0];
					this.lmsService.currentUserJourney = this.lmsService.userJourneysByAssignation.find(j => {
						return j.id === this.lmsService.userJourneyFromParams.id;
					});
					if (!this.lmsService.currentUserJourney) {
						this.lmsService.currentUserJourney = this.lmsService.allJourneys.find(j => {
							return j.id === this.lmsService.userJourneyFromParams.id;
						});
					}
					for (const j in this.originalAllJourneysByStatus) {
						if (j) {
							const posIndex = this.originalAllJourneysByStatus[j].items.findIndex(currJ => {
								return (
									currJ.id === this.lmsService.userJourneyFromParams.id &&
									currJ.journeyStatus !== this.lmsService.getStatusAsIndex(journeyStatus.allJourneys) &&
									currJ.journeyStatus === this.lmsService.userJourneyFromParams.journeyStatus
								);
							});
							if (posIndex > -1) {
								if (
									this.originalAllJourneysByStatus[j].items[posIndex].journeyStatus &&
									this.originalAllJourneysByStatus[j].items[posIndex].journeyStatus !==
									this.lmsService.getStatusAsIndex(journeyStatus.completed)
								) {
									const completedStatus = Object.keys(this.originalAllJourneysByStatus).find(key => {
										return key == this.lmsService.getStatusAsIndex(journeyStatus.completed);
									});
									if (completedStatus) {
										const pos = this.originalAllJourneysByStatus[completedStatus].items.findIndex(jStatus => {
											return jStatus.id === this.originalAllJourneysByStatus[j].items[posIndex].id;
										});
										if (pos === -1) {
											this.originalAllJourneysByStatus[completedStatus].items.push(
												this.originalAllJourneysByStatus[j].items[posIndex]
											);
										}
										this.originalAllJourneysByStatus[completedStatus].opened = true;
										if (this.originalAllJourneysByStatus[j].items[posIndex]) {
											this.originalAllJourneysByStatus[j].items.splice(posIndex, 1);
										}
									} else {
										this.originalAllJourneysByStatus[this.lmsService.getStatusAsIndex(journeyStatus.completed)] = {
											opened: true,
											items: new Array(this.originalAllJourneysByStatus[j].items[posIndex])
										};
									}
								}
							}
						}
					}
					this.globalService.fastBilanFinished = true;
					this.lmsService.currentUserJourney.start = true;
					LrsUtils.jounreyExerciseStep = this.lmsService.currentUserJourney.exercises[0].step;
					this.lrsService.createCabriStatementOnStartActivity();
					return;
				}
			} catch (err) {
				this.diagnostic = null;
			}
		}

		this.globalService.fastBilanFinished = false;
		if (this.lmsService.userJourneyFromParams) {
			this.defineSelectedActivity();
			if (this.lmsService.userJourneyFromParams.bilan) {
				this.selectedActivity.setParamValue("v-cursor-mod", "3");
				this.selectedActivity.paramHidden("v-cursor-mod", { 0: true, 1: true, 2: true });
			} else if (!this.lmsService.userJourneyFromParams.bilan) {
				if (this._activityContainTrainingMod) {
					this.selectedActivity.setParamValue("v-cursor-mod", "1");
					this.selectedActivity.paramHidden("v-cursor-mod", { 0: true, 1: false, 2: true, 3: true });
				}
			}
		}
		this.selectedActivity.params.forEach(item => {
			if (item.exercices) {
				if (item.value !== "0") {
					item.value = item.defaultValue;
				}
			}
		});

		this.cabriService.setSelectedActivity(this.selectedActivity);
		this.cabriService.defineExercice(this.selectedActivity);

		this.validateModal();
	}

	checkDiagnosticAvailability = () => {
		return new Promise<boolean>(async (resolve, reject) => {
			if (this.lmsService.userJourneyFromParams && this.lmsService.userJourneyFromParams.bilan) {
				const exercises = this.lmsService.addDiagnosticExercisesSteps(
					this.lmsService.userJourneyFromParams?.exercises,
					this.cabriService.exercices
				);
				const diagnosticResult: any = await this.accountService.diagnosticMode(exercises, this.accountService.team[0].id, true);
				if (!diagnosticResult.hasNextActivity) {
					// diagnosticResult hasn't next activity
					this.diagnostic = null;
					this.defineSelectedActivity();
					// if journey not in progress, set all exercises to status Done
					if (this.lmsService.journeyState && this.lmsService.journeyState[this.lmsService.userJourneyFromParams.id]) {
						this.lmsService.journeyState[this.lmsService.userJourneyFromParams.id].forEach(journey => {
							if (!journey.farthest) {
								journey.exercises.forEach(exercise => {
									exercise.status = Status.done;
								});
							}
						});
					}

					// message TTS + Toast for bilan.
					if (this.lmsService.userJourneyFromParams.bilan) {
						this.presentToast(diagnosticResult.message);
						this.playText(diagnosticResult.message);
					}
				} else {
					this.diagnostic = diagnosticResult;
					// Change all exercises status to done if prerequis not fulfilled or already mastered
					for (let i = 0; i < diagnosticResult.nextActivity.step; i++) {
						this.lmsService.userJourneyFromParams.exercises[i].status = Status.done;
					}
				}
				resolve(diagnosticResult);
			} else {
				reject();
			}
		});
	}
	/**
	 * Define selected activity based on journey's exercise to be executed
	 */
	defineSelectedActivity = () => {
		const journeyExercise: ProposedActivity = this.lmsService.userJourneyFromParams.selectJourneyExercise(
			this.lmsService.userJourneyFromParams.exercises,
			this.resume
		);

		this.selectedActivity = this.lmsService.userJourneyFromParams.defineJourneySelectedActivity(journeyExercise);
	}

	presentToast = async (message, duration = 2500) => {
		const toast = await this.lrsService.toastController.create({
			message,
			position: "bottom",
			duration
		});
		toast.present();
	}

	playText = (text: string, manual: boolean = false): Promise<void> => {
		return new Promise(async (resolve, reject) => {
			if (!this.globalService.playTTSService.menusMuted || manual) {
				this.globalService.playTTSService.playTTS(text).then(() => {
					resolve();
				});
			} else {
				setTimeout(() => {
					resolve();
				}, 1000);
			}
		});
	}

	validateModal = async () => {
		this.globalService.setGlobalLoading(true, this.globalService.isKidaia);
		if (this.selectedActivity) {
			this.selectedActivity.params.forEach(item => {
				if (item.exercices) {
					if (item.value && item.value !== "0") {
						item.value = item.defaultValue;
					} else {
						// Definir la valeur d'un exercice par défaut
						if (!item.defaultValue) {
							item.defaultValue = item.selectionList[0];
							item.value = item.selectionList[0][1];
						}
					}
				}
			});
		}

		// set journey params
		if (this.lmsService.userJourneyFromParams) {
			if (!this.lmsService.userJourneyFromParams.bilan) {
				// training mod
				await this.defineTrainingUserJourney(this.lmsService.userJourneyFromParams);
			} else if (this.lmsService.userJourneyFromParams.bilan) {
				// diagnostic mod
				await this.defineDiagnosticUserJourney(this.lmsService.userJourneyFromParams);
				if (this.selectedActivity) {
					// Hide bilan button from modal and display training mod
					this.selectedActivity.paramHidden("v-cursor-mod", { 3: true });
					// this.cd.detectChanges();
				}
			}

			if (this.lmsService.currentUserJourney) {
				this.lmsService.currentUserJourney.firstActivityDone = false;
			}
		}
		this.checkNeedChangeParams();

		this.selectedActivity.params.find(item => {
			if (item.name === "holo") {
				if (item.value === "1") {
					(window as any).Globals.Holo = 1;
					(window as any).params.append("holo", "1");
				} else if (item.value === "-1") {
					(window as any).Globals.Holo = -1;
					(window as any).params.append("holo", "-1");
				} else {
					// window.Globals.Holo = 0;
					(window as any).params.append("holo", "0");
				}
			}
		});

		// set activity
		this.cabriService.setSelectedActivity(this.selectedActivity);
		this.cabriService.defineExercice(this.selectedActivity);

		// reset gabarits page before leaving
		this.selectedActivity = null;
		this.checkNeedSaveJourney();

		this.playText($localize`En route pour une nouvelle aventure !`).then(() => {
			this.router.navigateByUrl(this.cabriService.currentActivity.routingPath, { replaceUrl: true });
		});
	}


	/**
	 * Define training journey
	 * @param currentJourney
	 */
	defineTrainingUserJourney = (currentJourney: Journey) => {
		return new Promise(async (resolve, reject) => {
			if (currentJourney.id) {
				if (this.lmsService.journeyState?.[currentJourney.id]) {
					this.lmsService.journeyState[currentJourney.id].find(async journeyState => {
						if (!journeyState.farthest && this.resume) {
							// Reprendre un parcours
							this.lmsService.currentUserJourney = await currentJourney.getResumedCurrentJourneyTrainingMod(journeyState);
							let currentJourneyExercisePos;
							LrsUtils.resume = true;
							if (journeyState.resumeExerciseProcessing(this.lmsService.currentUserJourney)) {
								// Reprendre un parcours lorsqu'un exercice est en cours d'être joué
								const lastQuestion =
									this.lmsService.currentUserJourney.allAskedQuestions[
									this.lmsService.currentUserJourney.allAskedQuestions.length - 1
									];
								currentJourneyExercisePos = this.lmsService.currentUserJourney.exercises.findIndex(
									(exercise: ProposedActivity) => {
										return exercise.step === lastQuestion.step;
									}
								);
							} else {
								// Reprendre un parcours lorsqu'un exercice a été terminé (Passage à l'exercice suivant)
								currentJourneyExercisePos = this.lmsService.currentUserJourney.exercises.findIndex(
									(exercise: ProposedActivity) => {
										return exercise.status === Status.notDone;
									}
								);
							}

							if (currentJourneyExercisePos > -1) {
								// const duration = this.lrsService.statement.durationResumedTrainingJourney(journeyState);
								const duration = this.lmsService.durationJourney(journeyState);
								if (duration) {
									this.lmsService.currentUserJourney.duration = duration;
								}

								if (!this.selectedActivity) {
									// définir l'activité à partir de l'index de l'exercice du parcours
									this.selectedActivity = journeyState.defineJourneySelectedActivity(
										journeyState.exercises[currentJourneyExercisePos]
									);
								}

								const exercise = this.cabriService.exercices.getExercise(
									journeyState.exercises[currentJourneyExercisePos].exerciseId
								);
								if (exercise) {
									this.selectedActivity.setParamValue("ex", exercise);
								}
								this.accountService.countAwards(this.resume, journeyState);
							} else {
								// sécurité ne doit pas executer ce cas.
								console.error("should not appear : ", journeyState.exercises[0]);
								if (!this.selectedActivity) {
									this.selectedActivity = journeyState.defineJourneySelectedActivity(journeyState.exercises[0]);
								}
								await this.cabriService.setActivityId(journeyState.exercises[0].exerciseId);
							}
						} else {
							// Commencer un parcours
							LrsUtils.idsession = null;
							this.lmsService.currentUserJourney = currentJourney.getStartedCurrentJourneyTrainingMod();
							LrsUtils.parcoursId = this.lmsService.currentUserJourney.id;
							LrsUtils.assignationId = this.lmsService.currentUserJourney.assignationId;
							LrsUtils.jounreyExerciseStep = this.lmsService.currentUserJourney.exercises[0].step;

							this.selectedActivity = this.lmsService.currentUserJourney.defineJourneySelectedActivity(
								currentJourney.exercises[0]
							);
							try {
								await this.cabriService.setActivityId(this.lmsService.currentUserJourney.exercises[0].exerciseId);
								// define exercise default value
							} catch (err) {
								console.error("first journey exercise not found");
								resolve(true);
							}
							// journey's awards
							this.accountService.countAwards(this.resume);
							// journey's awards
							resolve(true);
						}
						resolve(true);
					});
				} else {
					// S'il n'y a pas de parcours alors jouer l'exercice
					LrsUtils.resume = false;
					this.lmsService.currentUserJourney = currentJourney.getStartedCurrentJourneyTrainingMod();
					if (!this.selectedActivity) {
						this.selectedActivity = this.lmsService.currentUserJourney.defineJourneySelectedActivity(
							currentJourney.exercises[0]
						);
					}
					try {
						await this.cabriService.setActivityId(this.lmsService.currentUserJourney.exercises[0].exerciseId);
					} catch (err) {
						console.error("first journey exercise not found");
					}
					// journey's awards
					this.accountService.countAwards(this.resume);
					resolve(true);
				}
			} else {
				// journey's awards
				this.accountService.countAwards(this.resume);
				resolve(true);
			}
		});
	}


	/**
	 * Define diagnostic journey
	 */
	defineDiagnosticUserJourney = async (currentJourney: Journey) => {
		return new Promise<void>(async resolve => {
			const journey: Journey = currentJourney.getCurrentJourneyDiagnosticMod();
			this.lmsService.currentUserJourney = journey;
			try {
				await this.lmsService.currentUserJourney.checkNextDiagnosticExercise(this.diagnostic.nextActivity);
				this.diagnostic = null;
			} catch (err) {
				await this.lmsService.currentUserJourney.selectDiagnosticAsSimpleExercise();
				// Not any exercise
			}

			if (!this.selectedActivity) {
				this.selectedActivity = this.lmsService.currentUserJourney.defineJourneySelectedActivity(
					this.lmsService.currentUserJourney.exercises[0]
				);
			}
			this.accountService.countAwards(false);
			resolve();
		});
	}


	checkNeedSaveJourney = () => {
		// Sauvegarder l'état actuel du parcurs (modifié) avant le raffraîchissement
		this.accountService.saveUserJourney(this.resume ? false : true);
	}

	/**
	 * if necessary replace default params with general setting param
	 */
	checkNeedChangeParams = () => {
		this.selectedActivity.params.forEach(param => {
			for (const generalSettingParam in this.globalService.generalParamsValues) {
				if (generalSettingParam) {
					const valueParam = this.globalService.generalParamsValues[generalSettingParam];
					if (valueParam && valueParam.value && valueParam.param !== "remoteHost") {
						if (param.name === valueParam.name) {
							// return true if current param exist in activity param
							const containSelectedParam = param.selectionList.some(eachAvailableParam => {
								return eachAvailableParam[1] === valueParam.value;
							});
							if (
								!this.networkService.isConnected ||
								(param.name === "holo" && param.value === "-1" && !this.selectedActivity.hasPyramide)
							) {
								this.selectedActivity.setParamValue("holo", "0");
							}

							if (containSelectedParam) {
								this.selectedActivity.setParamValue(param.name, valueParam.value);
							}
						}
					}
				}
			}
		});
	}
}

results matching ""

    No results matching ""