const mongojs = require("mongojs");

function openDbFromUrl(mongoUrl, cb) {
  cb(null, mongojs(mongoUrl));
}

function copyCollection(source, target, collectionName, cb) {
  const sourceCollection = source.collection(collectionName);
  const targetCollection = target.collection(collectionName);
  sourceCollection.find().toArray((err3, results) => {
    if (err3) {
      console.error("error finding source results");
      cb(err3);
    } else {
      if (results && results.length > 0) {
        targetCollection.drop();
        targetCollection.insert(
          results,
          { upsert: true, new: true },
          (err4, docs) => {
            if (err4) {
              console.error(
                "error inserting target results ",
                collectionName,
                results
              );
              cb(err4);
            } else {
              cb(null, docs.length + " docs inserted");
            }
          }
        );
      } else {
        cb(null, 0 + " docs inserted");
      }
    }
  });
}

export const duplicateCollection = (sourceUrl, targetUrl, collectionName) => {
  return new Promise((resolve, reject) => {
    openDbFromUrl(sourceUrl, (err1, source) => {
      if (err1) {
        console.error("error opening source db");
        console.error(err1);
        resolve(false);
      } else {
        openDbFromUrl(targetUrl, (err2, target) => {
          if (err2) {
            console.error("error opening target db");
            console.error(err2);
            resolve(false);
          } else {
            copyCollection(source, target, collectionName, (err3, result) => {
              if (err3) {
                console.error("error copying collection");
                console.error(err3);
                resolve(true);
              } else {
                resolve(false);
              }
            });
          }
        });
      }
    });
  });
};
