/**
 * Returns a list of the candidate npm pack
 */
function getCandidatePackages() {
  const fs = require("fs");
  const glob = require("glob");
  const paths = require("../../paths");
  const { npmScope } = require("../../config");
  const globPath = `${npmScope}/*`;

  return glob.sync(globPath, { cwd: paths.nodeModules }).filter((file) => {
    const stat = fs.lstatSync(paths.join(paths.nodeModules, file), file);
    console.log(stat);
    return stat.isSymbolicLink();
  });
}

/**
 * Try npm link for each npm candidate package
 */
function tryNpmUnlink() {
  const packages = getCandidatePackages();
  const paths = require("../../paths");
  const { execSync } = require("child_process");

  packages.forEach((name, i) => {
    try {
      execSync(`npm unlink ${name}`, { cwd: paths.root });
    } catch (e) {
      console.warn(`Could not npm unlink package ${name}`);
    }
  });
}

/**
 * Returns a list of the listed packages in the directory
 */
// function getLinked() {
//   return glob.sync(globPath, { cwd: paths.nodeModules })
//   .map(match => match.slice(0, -1))
//   .filter(file => {
//     const stat = fs.lstatSync(path.join(paths.nodeModules, file));
//     return stat.isSymbolicLink();
//   });
// }

tryNpmUnlink();
