var glob = require("glob");

const { cleanPath } = require("../utilities/utils");

async function loadServices(config) {
  // Externes services
  try{
    if (config.services.length) {
      config.services.map((register) => {
           let _service_ = {};
          Object.keys(register()).forEach((key) => {
  
           key!=='name' ?  _service_[key] = register()[key]:null
          });
  
        if (register().name) {
          config.service[register().name] = _service_;
       }
        
      });
    }
  
    // Local services
    var Path = cleanPath(process.cwd() + "/extensions/services/**/index.js");
   
    return new Promise(function (resolve, reject) {
      glob(Path, {}, function (er, files) {
        // register all endpoints

        files.map((file) => {
          let register = require("" + file);
          let _service_ = {};
          let nameOfService = "";
  
       
  
          if (!register()["name"]) {
            let nameMissing = file.split("/");
            nameOfService = nameMissing[nameMissing.length - 2];
          } else {
            nameOfService = register()["name"];
          }

         
  
          Object.keys(register()).forEach((key) => {
            _service_[key] = register()[key];
          });
  
          config.service[nameOfService] = _service_;
        });
        // files is an array of filenames.
        // If the `nonull` option is set, and nothing
        // was found, then files is ["**/*.js"]
        // er is an error object or null.
       // consola.success(`${files.length} Services charged`);
        resolve();
      });
    });
  } catch(err){

    consola.error(err)
  }

  console.log('service => OK')
}


async function execServices({serviceName,req,res,config,params}){

  params = {
    async:false,
    ...params
  }

  
 try{
  let service = config.service[serviceName]
  //console.log(service,params.exec,service[params.exec])
 
  if(params.async){
    var response = await service[params?.exec](params?.args).then(e=>e)
  } else {
   var  response  = service[params?.exec](params?.args) 
   if(!response) response ={ok:true}
  }

 return res.send(response)
 } catch(err){
  
 return  res.status(400).send(err)
 }

}

module.exports = {
  loadServices,
  execServices
};
