let moment = require('moment')
module.exports = {


    friendlyName: 'Create',


    description: 'Create Information user!',


    inputs: {
        matiere: {
            type: 'string',
            required: true,
        },
        //codeEcole
        classe: {
            type: 'string',
            required: true,
        },
        dateEvaluation: {
            type: 'ref',
        },
        typeNote: {
            type: 'string',
            required: true,
        },
        //libDevoir
        trimSem: {
            type: 'string',
            required: true,
        },
        coef: {
            type: 'string',
            required: true,
        },

        //ordre
        //codMoy

        anneeScolaire: {
            type: 'string',
            required: true,
        },
        //codeNatureDevoir

        eleves: {
            type: 'ref'
        }

    },


    exits: {
        notFound: {
            statusCode: 404
        },
    },


    fn: async function (inputs, exits) {

        //console.log("INPUTS 1", inputs)
        const { /*id, */user } = this.req.token;

        //console.log("INPUTS", inputs)
        let userCodeEcole;
        if (user.typeUser === 'ENSEIGNANT' || user.typeUser === 'ADMINISTRATION' || user.typeUser === 'ADMIN' || user.typeUser === 'SECRETARIAT') {
            userCodeEcole = user.codeEcole
        } else {
            return exits.notFound({ message: "Vous n'etes pas autoriser a accéder a cette page!" })

        }

        // VERIFICATION DU CODE ECOLE
        if (user.codeEcole === '' || user.codeEcole === null || user.codeEcole === undefined) {
            return exits.notFound({ message: "Veuillez préciser le code Ecole pour cet utulisateur pour a accéder a cette page!" })
        }
        ecoleVerif = await Ecoles.find({ codeEcole: user.codeEcole }).then(_.first)
        if (!ecoleVerif) {
            return exits.notFound({ message: "Cet utilisateur n'est attribué a aucune ecole!" })
        }
        // FIN VERIF CODE ECOLE

        inputs.codeEcole = userCodeEcole
        ///////////////////

        let ouestDate = moment.utc(new Date()).utcOffset('+01:00')
        inputs.dateEnregistrement = moment(ouestDate, 'DD/MM/YYYY').format('YYYY-MM-DD')
        inputs.heureEnregistrement = moment(ouestDate).format('HH:mm:ss')

        let lastIdAuto = await ProfNote.find().sort('id DESC').then(_.first)

        let id;
        if (!lastIdAuto) {
            id = 1
        } else {
            var codeStr = lastIdAuto.codMoy;

            codeStr = codeStr.replace('WEB', '');
            id = parseFloat(codeStr) + 1
        }

        let codeCreate;
        //console.log('ID', id)


        if (id < 10) {
            codeCreate = `WEB000${id}`
        }

        if (id >= 10 && id < 100) {
            codeCreate = `WEB00${id}`
        }

        if (id >= 100 && id < 1000) {
            codeCreate = `WEB0${id}`
        }

        if (id >= 1000) {
            codeCreate = `WEB${id}`
        }

        inputs.codMoy = codeCreate

        let notesVerify = await ProfNote.find({ codMoy: inputs.codMoy }).then(_.first)

        if (notesVerify) {
            return exits.notFound({ message: "Ce code existe déja, veuillez le modifier!" })
        }
        //console.log('type note', inputs.typeNote)

        // VERIFIER SI NOTES PAS DÉJA RENSEIGNER UNE FOIS
        let notesVerify2 = await ProfNote.find({
            codeEcole: userCodeEcole,
            codeClasse: inputs.classe,
            codeMatiere: inputs.matiere,
            typeNote: inputs.typeNote,
            trimSem: inputs.trimSem,
            anneeScolaire: inputs.anneeScolaire,
        }).then(_.first)

        if (notesVerify2) {
            return exits.notFound({ message: "Il y a déja une note saisir pour cette matiere et ce type de devoir, veuillez la modifier!" })
        }

        let libDevoir;
        let ordre;
        let codeNatureDevoir;

        if (inputs.typeNote === 'I1') {
            libDevoir = '1ère Interrogation'
            ordre = '1'
            codeNatureDevoir = '04'
            typeDev = 'I'
        }
        if (inputs.typeNote === 'I2') {
            libDevoir = '2ème Interrogation'
            ordre = '2'
            codeNatureDevoir = '05'
            typeDev = 'I'

        }
        if (inputs.typeNote === 'I3') {
            libDevoir = '3ème Interrogation'
            ordre = '3'
            codeNatureDevoir = '06'
            typeDev = 'I'

        }
        if (inputs.typeNote === 'I4') {
            libDevoir = '4ème Interrogation'
            ordre = '4'
            codeNatureDevoir = '07'
            typeDev = 'I'

        }
        if (inputs.typeNote === 'I5') {
            libDevoir = '5ème Interrogation'
            ordre = '5'
            codeNatureDevoir = '08'
            typeDev = 'I'

        }
        if (inputs.typeNote === 'D1') {
            libDevoir = 'Devoir'
            ordre = '7'
            codeNatureDevoir = '02'
            typeDev = 'D'
        }
        if (inputs.typeNote === 'D2') {
            libDevoir = 'Compo'
            ordre = '8'
            codeNatureDevoir = '03'
            typeDev = 'D'
        }
       /* if (inputs.typeNote === 'D3') {
            libDevoir = 'Devoir 3'
            ordre = '8'
            codeNatureDevoir = '02'
            typeDev = 'D'
        }*/
        if (inputs.typeNote === 'M1') {
            libDevoir = 'MoyInt'
            ordre = '6'
            codeNatureDevoir = '01'
            typeDev = 'M'
        }

        let notes = await ProfNote.create({
            codMoy: inputs.codMoy,

            codeMatiere: inputs.matiere,
            codeClasse: inputs.classe,
            dateEvaluation: moment(inputs.dateEvaluation, 'DD-MM-YYYY').format('YYYY-MM-DD'),
            codeEnseignant: user.codeUser,
            typeNote: inputs.typeNote,
            libDevoir: libDevoir,
            ordre: ordre,
            codeNatureDevoir: codeNatureDevoir,
            dateEnregistrement: inputs.dateEnregistrement,
            heureEnregistrement: inputs.heureEnregistrement,
            codeEcole: inputs.codeEcole,
            anneeScolaire: inputs.anneeScolaire,
            trimSem: inputs.trimSem,
            idMatTrimNatureClasse: `${inputs.matiere},${inputs.trimSem},${codeNatureDevoir},${inputs.classe}`,
            idClasseMatTrim: `${inputs.classe},${inputs.matiere},${inputs.trimSem}`,
            typeDev: typeDev,
            coef: inputs.coef

        }).fetch()

        let classeSelect = await AttributionMatiere.find({ codeMatiere: inputs.matiere }).then(_.first)
        console.log('classeSelect', classeSelect)
        let libelleCourt = classeSelect.libelleCourt
        let libelleLong = classeSelect.libelleLong

        let details = []
        if (inputs.eleves && inputs.eleves.length > 0) {
            for (let i = 0; i < inputs.eleves.length; i++) {

                let detail = await ProfNoteDetails.create({
                    //id: `${sequenceReparation}`,

                    codMoy: inputs.codMoy,

                    codeMatiere: inputs.matiere,
                    matricule: inputs.eleves[i].matricule,
                    codeClasse: inputs.classe,
                    libelleCourt: libelleCourt,
                    libelleLong: libelleLong,
                    typeNote: 'NOTE',
                    note: inputs.eleves[i].note || '',
                    status: inputs.eleves[i].status,
                    presence: inputs.eleves[i].status === "PRESENT" ? "1" : inputs.eleves[i].status === "ABSCENT" ? "2" : '', //
                    coef: inputs.coef,
                    trimSem: inputs.trimSem,

                    codeEcole: inputs.codeEcole,
                    anneeScolaire: inputs.anneeScolaire,
                    codElvCodMoy: `${inputs.eleves[i].matricule},${notes.codMoy}`

                }).fetch()

                if (detail) {
                    details.push(detail)
                }
            }
        }
        return exits.success(_.merge(notes));
        // All done.
    }
};
