/**
 * Seed Function
 * (sails.config.bootstrap)
 *
 * A function that runs just before your Sails app gets lifted.
 * > Need more flexibility?  You can also create a hook.
 *
 * For more information on seeding your app with fake data, check out:
 * https://sailsjs.com/config/bootstrap
 */


module.exports.bootstrap = async function (done) {

  // By convention, this is a good place to set up fake data during development.
  //
  // For example:
  // ```
  // // Set up fake development data (or if we already have some, avast)
  // if (await User.count() > 0) {
  //   return;
  // }
  //
  // await User.createEach([
  //   { emailAddress: 'ry@example.com', fullName: 'Ryan Dahl', },
  //   { emailAddress: 'rachael@example.com', fullName: 'Rachael Shaw', },
  //   // etc.
  // ]);
  // ```

  // DOSSIER DES IMAGES

  var path = require('path');



  /*****************************
  
  
    // This bootstrap version indicates what version of fake data we're dealing with here.
    var HARD_CODED_DATA_VERSION = 0;
  
    // This path indicates where to store/look for the JSON file that tracks the "last run bootstrap info"
    // locally on this development computer (if we happen to be on a development computer).
    var bootstrapLastRunInfoPath = path.resolve(sails.config.appPath, '.tmp/bootstrap-version.json');
  
    // Whether or not to continue doing the stuff in this file (i.e. wiping and regenerating data)
    // depends on some factors:
    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  
    // If the hard-coded data version has been incremented, or we're being forced
    // (i.e. `--drop` or `--environment=test` was set), then run the meat of this
    // bootstrap script to wipe all existing data and rebuild hard-coded data.
    if (sails.config.models.migrate !== 'drop' && sails.config.environment !== 'test') {
      // If this is _actually_ a production environment (real or simulated), or we have
      // `migrate: safe` enabled, then prevent accidentally removing all data!
      if (process.env.NODE_ENV==='production' || sails.config.models.migrate === 'safe') {
        sails.log.warn('Since we are running with migrate: \'safe\' and/or NODE_ENV=production (in the "'+sails.config.environment+'" Sails environment, to be precise), skipping the rest of the bootstrap to avoid data loss...');
        //return done();
      }//•
  
      // Compare bootstrap version from code base to the version that was last run
      var lastRunBootstrapInfo = await sails.helpers.fs.readJson(bootstrapLastRunInfoPath)
      .tolerate('doesNotExist');// (it's ok if the file doesn't exist yet-- just keep going.)
  
      if (lastRunBootstrapInfo && lastRunBootstrapInfo.lastRunVersion === HARD_CODED_DATA_VERSION) {
        sails.log('Skipping v'+HARD_CODED_DATA_VERSION+' bootstrap script...  (because it\'s already been run)');
        sails.log('(last run on this computer: @ '+(new Date(lastRunBootstrapInfo.lastRunAt))+')');
        //return done();
      }//•
  
      sails.log('Running v'+HARD_CODED_DATA_VERSION+' bootstrap script...  ('+(lastRunBootstrapInfo ? 'before this, the last time the bootstrap ran on this computer was for v'+lastRunBootstrapInfo.lastRunVersion+' @ '+(new Date(lastRunBootstrapInfo.lastRunAt)) : 'looks like this is the first time the bootstrap has run on this computer')+')');
    }
    else {
      sails.log('Running bootstrap script because it was forced...  (either `--drop` or `--environment=test` was used)');
    }
  
    // Since the hard-coded data version has been incremented, and we're running in
    // a "throwaway data" environment, delete all records from all models.
   
  
    // By convention, this is a good place to set up fake data during development.
   
  
    // Save new bootstrap version
    await sails.helpers.fs.writeJson.with({
      destination: bootstrapLastRunInfoPath,
      json: {
        lastRunVersion: HARD_CODED_DATA_VERSION,
        lastRunAt: Date.now()
      },
      force: true
    })
    .tolerate((err)=>{
      sails.log.warn('For some reason, could not write bootstrap version .json file.  This could be a result of a problem with your configured paths, or, if you are in production, a limitation of your hosting provider related to `pwd`.  As a workaround, try updating app.js to explicitly pass in `appPath: __dirname` instead of relying on `chdir`.  Current sails.config.appPath: `'+sails.config.appPath+'`.  Full error details: '+err.stack+'\n\n(Proceeding anyway this time...)');
    });
  
    // Don't forget to trigger `done()` when this bootstrap function's logic is finished.
    // (otherwise your server will never lift, since it's waiting on the bootstrap)
    //return done();

    // Initialisation des abonnements supprimée (déplacée dans setTimeout)
  
  
  
  
  
  
  *********************************/

  /*let pass;
  await sails.config.cryptoUtils.encrypt('Corossol@Gestion',function (err, msg){
    if(err){
      throw 'encryptionError';
    }
    pass = msg
  })*/

  //let pass = 'Perlene@Solution'

  // ADMIN
  sails.on('hook:cron:loaded', () => {
    sails.log.info('Cron hook is ready, tasks will start automatically');
  });

  // Si vous voulez un délai spécifique avant le démarrage
  setTimeout(async () => {
    sails.log.info('Application bootstrap start');
    try {
      const initAbos = require('../scripts/init-abonnements');
      await initAbos();
    } catch (e) {
      sails.log.error('Erreur init abonnements:', e);
    }
    sails.log.info('Application bootstrap complete');
  }, 5000);


  let adminUser = await Utilisateurs.find({ login: 'AdminCorossol', codeVerif: 'CoroMe@23' }).then(_.first)
  //console.log('admin found, role', adminUser,adminRole)
  if (!adminUser) {

    let lastIdUser = await Utilisateurs.find().sort('id DESC').then(_.first)

    let idUser;
    if (!lastIdUser) {
      idUser = 1
    } else {
      idUser = parseInt(lastIdUser.id) + 1 || 1
    }

    adminUser = await Utilisateurs.create({
      id: idUser,
      login: 'AdminCorossol',
      //codeUser: '12345678900',
      codeVerif: 'CoroMe@23',
      codeUser: '&Corossol@!Gestion?',
      nom: 'Super ADMIN',
      email: 'contact@evolutiosystem.com',
      telephone1: '97598736',
      indicatif1: '229',
      typeUser: 'ADMIN',
      codeEcole: 'E0001'


    }).fetch()
    //await User.update(adminUser.id, { role: adminRole.id })

  }

  //TRIMESTRE SEMESTE
  let trimSem = await Trimestre.find({ label: 'Trimestre 1' })
  if (trimSem.length < 1) {
    trimSem = await Trimestre.createEach([
      { label: 'Trimestre 1', value: '1', enCours: true },
      { label: 'Trimestre 2', value: '2', enCours: false },
      { label: 'Trimestre 3', value: '3', enCours: false }

    ]).fetch()
  }
  return done();
};
