const functions = require('firebase-functions');
var admin = require("firebase-admin");


const firestore = admin.firestore();
const path = require("path");
const fs = require("fs");
const directoryPath = path.join(__dirname, "db_seed");

exports.dbSeed = functions.https.onRequest(async (request, response) => {
  try {
    fs.readdir(directoryPath, function (err, files) {
      if (err) {
        return console.log("Unable to scan directory: " + err);
      }

      files.forEach(function (file) {
        var lastDotIndex = file.lastIndexOf(".");

        var menu = require("./db_seed/" + file);

        menu.forEach(function (obj) {
          firestore
            .collection(file.substring(0, lastDotIndex))
            .add(obj)
            .then(function (docRef) {
              console.log("Document written");
            })
            .catch(function (error) {
              console.error("Error adding document: ", error);
            });
        });
      });
    });

  } catch (e) {
    throw response.status(400).send("sorry Error : " + e);
  }

  // Return a 200 response to acknowledge receipt of the event
  response.send();
});
