import { Question } from "../classes/question";
import { Utilisateur } from "../models/utilisateur";

export class QuestionControleur {

    private _questions: Map<string, Question>;
    
    constructor() {
        this._questions = new Map<string, Question>();
        this.ajouterQuestion("LOG121", "Test", "RDCU", "C'est quoi un RDCU?", true, "Bien joué", "Mal joué", "cc-vincent.lacasse@etsmtl.ca")
        this.ajouterQuestion("LOG121", "Test", "DSS", "C'est quoi un DSS?", true, "Bien joué", "Mal joué", "cc-vincent.lacasse@etsmtl.ca")
        this.ajouterQuestion("LOG121", "Test", "Contrat", "C'est quoi un Contrat?", true, "Bien joué", "Mal joué", "cc-vincent.lacasse@etsmtl.ca")
    }

    public recupererQuestions() {
        return this._questions;
    }

    public recupererQuestion(nom: string, enseignant: string) {
        const nomID = enseignant + nom;

        return this._questions.get(nomID);
    }

    public ajouterQuestion(cours: string, categorie: string, nom: string, enonce: string, reponse: boolean,
                        retroactionPostive: string, retroactionNegative: string, auteur: string): string {

        if (this.isEmpty(nom)) {
            let msg = "Le nom de la question ne peut pas etre vide";
            console.error(msg);
            throw new Error(msg);
        }

        if (this._questions.get(nom)) {
            let msg = `La question ${nom} existe déjà`;
            console.error(msg);
            throw new Error(msg);
        }
        
        const question = new Question(cours, categorie, nom, enonce, reponse,
                                    retroactionPostive, retroactionNegative, auteur);
        this._questions.set(auteur + nom, question);

        return JSON.stringify(question);
    }

    public isEmpty(str: string): boolean{
        return str === null || str.length === 0 || str.match(/^ *$/) !== null;
    }

    public modifierQuestion(ancienNom: string, cours: string, categorie: string, nom: string, enonce: string, reponse: boolean,
        retroactionPostive: string, retroactionNegative: string, auteur: string): string {

        if (ancienNom !== nom && this._questions.get(nom)) {
            let msg = `La question ${nom} existe déjà`;
            console.error(msg);
            throw new Error(msg);
        }

        this._questions.delete(ancienNom);
        const question = new Question(cours, categorie, nom, enonce, reponse,
                            retroactionPostive, retroactionNegative, auteur);
        this._questions.set(nom, question);

        return JSON.stringify(question);
    }

    public supprimerQuestion(nom: string, user: Utilisateur): boolean {
        return this._questions.delete(`${user.id}${nom}`);
    }
}