const fs = require("fs");
const path = require("path");
const { src, dest, task, watch, series } = require('gulp');
const Gitdown = require('@gnd/gitdown');
const rename = require("gulp-rename");
const debug = require("gulp-debug");
const pandoc = require("gulp-pandoc");

task('gitdown', async () => {
  if (!fs.existsSync("dist")) {
    fs.mkdirSync("dist");
  }

  const gitdown = Gitdown.readFile(path.join(__dirname, "src", "index.md"));

  gitdown.registerHelper("scroll-up", {
    compile: (config) => {
      return "<sup>[ [^](#user-content-contents) _Back to contents_ ]</sup>";
    }
  });

  await gitdown.writeFile('dist/_merged.md');
});

task('pandoc', () => {
  return src("dist/_merged.md")
    .pipe(debug({ title: "merged" }))
    .pipe(pandoc({
      from: "gfm",
      to: "gfm",
      args: ['--wrap=none'],
      ext: "md"
    }))
    .pipe(debug({ title: "pandoc output:" }))
    .pipe(rename("output.md"))
    .pipe(dest("dist"));
});

task('build', series("gitdown", "pandoc"));

task('watch', series(["build", () => {
  watch('./src', series(['build']));
}]));


task('default', series('build'));

@@ -504,16 +504,195 @@
 g) =%3E %7B%0A
+      if (config.downRef) %7B%0A        return %60%3Csup%3E%5B %5B&and;%5D(#user-content-contents) _Back to contents_ %7C _$%7Bconfig.downTitle%7D_ %5B&or;%5D($%7Bconfig.downRef%7D) %5D%3C/sup%3E%60;%0A      %7D else %7B%0A  
       re
@@ -709,9 +709,13 @@
 %3E%5B %5B
-%5E
+&and;
 %5D(#u
@@ -765,16 +765,24 @@
 /sup%3E%22;%0A
+      %7D%0A
     %7D%0A  

Make scroll-up thingy support scroll-down thingy