'use strict';
const crypto = require('crypto');
const fs = require('fs')
/**
 * generates the runtime executor after inserting the received function
 * TODO: make this asynchronous
 * @param {string Path from where to extract the function} functionPath 
 * @param {string Function Hash value} functionHash 
 */
 function generateExecutor(functionPath, functionHash) {
    //creating function.c
      let function_temp = fs.readFileSync(`./repository/worker_env/function_temp.c`)
      let function_def = fs.readFileSync(functionPath + functionHash)
      let searchSize = "//ADD_FUNCTION".length
      
      let insertIndex = function_temp.indexOf("//ADD_FUNCTION") + searchSize
      let function_name = "void function_"+functionHash.slice(0,-2) +"(PIF_PLUGIN_map_hdr_T *mapHdr)"
      let full_function = function_temp.slice(0, insertIndex) +"\n"+ function_name + "{\n" +function_def +"\n}"+ function_temp.slice(insertIndex)
     
      let hash = crypto.createHash('md5').update(full_function).digest("hex");
      console.log(hash);
      console.log(full_function);
      fs.writeFileSync(functionPath + hash + ".c", full_function)
   
   //adding call to function when match with fid
   return new Promise((resolve) => {
   let main_function_temp = fs.readFileSync(`./repository/worker_env/microc_temp.c`)
      let client_function = fs.readFileSync(functionPath + hash+".c")
      searchSize = "//ADD_FUNCTION_EXTERNS".length
      insertIndex = main_function_temp.indexOf("//ADD_FUNCTION_EXTERNS") + searchSize
      let extern_name = "extern void function_"+functionHash.slice(0,-2) +"(PIF_PLUGIN_map_hdr_T *mapHdr)"
      let main_function = main_function_temp.slice(0, insertIndex) +"\n"+ extern_name+";\n"+ main_function_temp.slice(insertIndex)
     console.log("MAIN FUNCTION : \n",main_function)
      // let hash = crypto.createHash('md5').update(full_function).digest("hex");
      // console.log(hash);
      searchSize = "//ADD_FUNCTION_CONDITION".length
      insertIndex = main_function.indexOf("//ADD_FUNCTION_CONDITION") + searchSize
      let fid = parseInt(hash.slice(0,5), 16)
      let if_else_cond = "else if( fid == "+fid + " ) {\nfunction_"+functionHash.slice(0,-2) +"(mapHdr);\n}"
      let main_function_full = main_function.slice(0, insertIndex) +"\n"+ if_else_cond +"\n"+ main_function.slice(insertIndex)
     

      console.log(main_function_full);
      fs.writeFileSync("/home/pcube/nilanjan/xanadu/dispatch_system/dispatch_manager/repository/nic_functions/static_dispatch_function.c", main_function_full)
      return hash
   });
}
 
 generateExecutor("/home/pcube/nilanjan/xanadu/dispatch_system/dispatch_manager/repository/nic_functions/","5a17c161093a69b37638148943b8810b.c")