const paths = require("../../paths");
const { npmScope } = require("../../config");
const glob = require("glob");
const globPath = `${npmScope}/*`;

/**
 * Returns a list of the candidate npm pack
 */
function getCandidatePackages() {
  return glob.sync(globPath, { cwd: paths.nodeModules }).filter((file) => {
    const stat = fs.lstatSync(file);
    return stat.isSymbolicLink();
  });
}

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

  packages.forEach((name) => {
    try {
      execSync(`npm unlink ${name}`, { cwd: paths.root });
    } catch (e) {
      console.warn(`Could not npm link 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();
