const fs = require("fs");
const path = require("path");

function postOrderDirectoryTraverse(dir, dirCallback, fileCallback) {
  for (const filename of fs.readdirSync(dir)) {
    if (filename === ".git") {
      continue;
    }
    const fullPath = path.resolve(dir, filename);
    if (fs.lstatSync(fullPath).isDirectory()) {
      postOrderDirectoryTraverse(fullPath, dirCallback, fileCallback);
      dirCallback(fullPath);
      continue;
    }
    fileCallback(fullPath);
  }
}

function emptyDir(dir) {
  if (!fs.existsSync(dir)) {
    return;
  }

  postOrderDirectoryTraverse(
    dir,
    (dir) => fs.rmdirSync(dir),
    (file) => fs.unlinkSync(file),
  );
}

module.exports = {
  copyFolder(source, target) {
    if (source === target) {
      return;
    }

    try {
      fs.cpSync(source, target, { recursive: true });
    } catch (error) {
      console.log(error.message);
    }
  },

  ifEmpty(dir) {
    if (!fs.existsSync(dir)) {
      return true;
    }

    const files = fs.readdirSync(dir);
    return files.length === 0 || (files.length === 1 && files[0] === ".git");
  },

  prepareFolder(targetFolder, shouldOverwrite) {
    if (fs.existsSync(targetFolder) && shouldOverwrite) {
      emptyDir(targetFolder);
    } else if (!fs.existsSync(targetFolder)) {
      fs.mkdirSync(targetFolder);
    }
  },

  renameFile(targetFolder, targetFile, sourceFile) {
    fs.renameSync(path.join(targetFolder, targetFile), path.join(targetFolder, sourceFile))
  },
};