const chokidar = require("chokidar");
const Grapefruit = require("grapefruit");
const careless = require("careless-fs");
const buildPipeline = require("./build-pipeline");
const fs = require("fs");

const logfilePath = "./last-build.log";
const log = fs.createWriteStream(logfilePath, { flags: "w" });

const runner = new Grapefruit({
  emitter: event => {
    log.write(JSON.stringify(event, null, 2));
    log.write("\n");
  },
  funcs: {
    listDirectory: require("./funcs/listDirectory.js"),
    imageMin: require("./funcs/imageMin.js"),
    decorateFileObject: require("./funcs/decorateFileObject.js"),
    readInFile: require("./funcs/readInFile.js"),
    copyFileTo: require("./funcs/copyFileTo.js"),
    minifyHtml: require("./funcs/minifyHtml.js"),
    minifyJS: require("./funcs/minifyJS.js"),
    writeOutFile: require("./funcs/writeOutFile.js"),
    compileTemplates: require("./funcs/compileTemplates.js"),
    renderTemplate: require("./funcs/renderTemplate.js"),
    markdownToHtml: require("./funcs/markdownToHtml.js"),
    parseJson: require("./funcs/parseJson.js"),
    rmrf: require("./funcs/rmrf.js"),
    gitAdded: require("./funcs/gitAdded.js"),
    copy: require("./funcs/copy.js")
  }
});

async function build() {
  const pipeline = runner.runPipeline(buildPipeline);
  pipeline
    .then(function(res) {
      console.log("Pipeline complete.");
      console.log(`History written to ${logfilePath}`);
      return res;
    })
    .catch(function(err) {
      console.log(
        "Pipeline error:",
        err.message
          ? JSON.stringify(err.message, null, 2)
          : JSON.stringify(err, null, 2)
      );
      console.log(`History written to ${logfilePath}`);
      return err;
    });
}

build();

const watcher = chokidar.watch("./content", {
  ignored: /[\/\\]\./,
  persistent: true,
  ignoreInitial: true,
  followSymlinks: true,
  cwd: ".",
  disableGlobbing: false,

  usePolling: false,
  interval: 100,
  binaryInterval: 300,
  alwaysStat: false,
  depth: 99,
  awaitWriteFinish: {
    stabilityThreshold: 2000,
    pollInterval: 100
  }
});

watcher.on("all", function(event) {
  build();
});
