// @ts-check
const partialFilenameOriginal = "svgicons.svg";

/**
 * Generate svg inline html definitions from svg images
 */
function svgiconsGenerate() {
  const path = require("path");
  const gulp = require("gulp");
  const svgstore = require("gulp-svgstore");
  const svgmin = require("gulp-svgmin");
  const paths = require("../paths");

  return (
    gulp
      .src(paths.join(paths.frontend.src.svgicons, "*.svg"))
      .pipe(
        svgmin((file) => {
          const prefix = path.basename(
            file.relative,
            path.extname(file.relative)
          );
          return {
            plugins: [
              {
                removeViewBox: false,
                cleanupIDs: {
                  prefix: prefix + "-",
                  minify: true,
                },
              },
            ],
          };
        })
      )
      // .pipe(rename({ prefix: 'icon-' }))
      .pipe(svgstore({ inlineSvg: true }))
      .pipe(gulp.dest(paths.frontend.src.svgicons))
  );
}

/**
 * Use generated inline svg as template partial to include in base layout
 */
function svgiconsPartial() {
  const gulp = require("gulp");
  const header = require("gulp-header");
  const footer = require("gulp-footer");
  const rename = require("gulp-rename");
  const paths = require("../paths");
  const config = require("../config");
  const { getHeaderAutogeneration, getHiddenCss } = require("../utils");

  return (
    gulp
      .src(paths.join(paths.frontend.src.svgicons, partialFilenameOriginal), {
        allowEmpty: true,
      })
      .pipe(header(`<div aria-hidden="true" style="${getHiddenCss()}">`))
      .pipe(header(`{{-- ${getHeaderAutogeneration()} --}}\n\n`))
      // @ts-ignore
      .pipe(footer(`</div>`))
      .pipe(rename(config.filenames.svgIconsPartial))
      .pipe(gulp.dest(paths.frontend.dest.automated))
  );
}

/**
 * Clean up the `gulp-svgstore`'s auto-generated `.html` file (renamed in
 * `blade.php` and tweaked from the above task).
 */
function svgiconsClean() {
  const del = require("del");
  const paths = require("../paths");

  return del(paths.join(paths.frontend.src.svgicons, partialFilenameOriginal));
}

/**
 * Collect subtasks in a single task that respect the gulp async lifecycle by
 * calling the callback on completion.
 */
module.exports = function svgicons(callback) {
  const gulp = require("gulp");

  return gulp.series(
    svgiconsGenerate,
    svgiconsPartial,
    svgiconsClean
  )(callback);
};
