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


    friendlyName: 'Create',


    description: 'Create Information user!',


    inputs: {
        classe: {
            type: 'string',
            required: true
        },
        matiere: {
            type: 'string',
            required: true
        },
        dateCours: {
            type: 'string',
            required: true

        },

        heureDebutCours: {
            type: 'string',
            required: true

        },
        heureFinCours: {
            type: 'string',
            required: true
        },
        anneeScolaire: {
            type: 'string',
            required: true
        },
        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') {
            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 AbscencePresence.find().sort('id DESC').then(_.first)

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

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

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


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

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

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

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

        inputs.codeAbscence = codeCreate

        let presenceVerify = await AbscencePresence.find({ codeAbscence: inputs.codeAbscence }).then(_.first)

        if (presenceVerify) {
            return exits.notFound({ message: "Ce code existe déja, veuillez le modifier!" })
        }

        inputs.dateCours = moment(inputs.dateCours, 'DD/MM/YYYY').format('YYYY-MM-DD')

        let presenceVerifyDate = await AbscencePresence.find({ dateCours: inputs.dateCours, codeClasse: inputs.classe, codeMatiere:inputs.matiere}).then(_.first)

        if (presenceVerifyDate) {
            return exits.notFound({ message: "Il y a déja un appel pour cette Date, ce cours et classe, veuillez le modifier!" })
        }


        let presence = await AbscencePresence.create({
            codeAbscence: inputs.codeAbscence,

            codeMatiere: inputs.matiere,
            codeClasse: inputs.classe,
            codeEnseignant: user.codeUser,
            dateCours: inputs.dateCours ,
            heureDebutCours: inputs.heureDebutCours,
            heureFinCours: inputs.heureFinCours,
            dateEnregistrement: inputs.dateEnregistrement,
            heureEnregistrement: inputs.heureEnregistrement,
            //observation: inputs.montantTtc,
            codeEcole: inputs.codeEcole,
            anneeScolaire: inputs.anneeScolaire,

        }).fetch()

        let details = []
        if (inputs.eleves && inputs.eleves.length > 0) {
            for (let i = 0; i < inputs.eleves.length; i++) {
                let detail = await AbscencePresenceDetails.create({
                    //id: `${sequenceReparation}`,

                    codeAbscence: inputs.codeAbscence,

                    matricule: inputs.eleves[i].matricule,
                    abscent: inputs.eleves[i].abscent,
                    motif: inputs.eleves[i].motif,
                    retard: inputs.eleves[i].retard,
                    heureRetard: inputs.eleves[i].heureRetard,
                    motifRetard: inputs.eleves[i].motifRetard,
                    depart: inputs.eleves[i].depart,
                    heureDepart: inputs.eleves[i].heureDepart,
                    motifDepart: inputs.eleves[i].motifDepart,
                    observation: inputs.eleves[i].observation,
                    codeEcole: inputs.codeEcole,
                    anneeScolaire: inputs.anneeScolaire,

                }).fetch()

                if (detail) {
                    details.push(detail)
                }
            }
        }

        return exits.success(_.merge(presence));
        // All done.


    }


};
