module.exports = {


    friendlyName: 'Create',


    description: 'Create Attribution rang!',


    inputs: {
        nom: {
            type: 'string',
            required: true
        },
        pays: {
            type: 'string',
        },

        ville: {
            type: 'string',
        },
        description: {
            type: 'string',
        },

        /*codeEcole: {
            type: 'string',
        },*/

    },


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


    fn: async function (inputs, exits) {

        //console.log("INPUTS 1", inputs)

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

        let id;
        if (!lastIdAuto) {
            id = 1
        } else {
            var codeEcoleStr = lastIdAuto.codeEcole;
        console.log('codeEcoleStr', codeEcoleStr)


            codeEcoleStr = codeEcoleStr.replace('E', '');
            console.log(codeEcoleStr);

            id = parseFloat(codeEcoleStr) + 1
        }

        let codeEcole;
        console.log('ID', id)
        

        if (id < 10) {
            codeEcole = `E000${id}`
        }

        if (id >= 10 && id < 100) {
            codeEcole = `E00${id}`
        }

        if (id >= 100 && id < 1000) {
            codeEcole = `E0${id}`
        }

        if (id >= 1000 ) {
            codeEcole = `BC${id}`
        }

        inputs.codeEcole = codeEcole
        ///////////////////
        
        let ecoleCode = await Ecoles.find({codeEcole: inputs.codeEcole }).then(_.first)
        
        if (ecoleCode) {

            return exits.notFound({ message: "Ce code existe déja pour une école, veuillez la modifier!" })
        }
        let ecoles = await Ecoles.find({ nom: inputs.nom}).then(_.first)
       
        if (ecoles) {

            return exits.notFound({ message: "Cette école existe déja, veuillez la modifier!" })
        } else {
            let ecolesCreate = await Ecoles.create(inputs).fetch();
            return exits.success(_.merge(ecolesCreate));
        }
        // All done.
        

    }


};
