// @ts-check

/**
 * Get JavaScript types info about path and locations within the current
 * project and within this library.
 *
 * @returns
 */
function getJsTypesInfo() {
  const paths = require("../paths");
  const destPath = paths.self.tmp;

  return {
    fileName: "globals.d.ts",
    destPath,
  };
}

/**
 * Create basic global types made available by this scripts to the project,
 * tsconfig.json will include a path to these types.
 */
function configureJsTypes(callback) {
  const gulp = require("gulp");
  const template = require("gulp-template");
  const rename = require("gulp-rename");
  const paths = require("../paths");
  const { cliPkg } = require("../config");
  const { getProjectSlug, getProjectJsGlobals } = require("../utils");
  const globals = getProjectJsGlobals();
  const typesInfo = getJsTypesInfo();

  return (
    gulp
      .src(paths.join(paths.self.templates, typesInfo.fileName))
      // @ts-ignore
      .pipe(template({ globals, packageName: cliPkg.name }))
      .pipe(rename("index.d.ts"))
      .pipe(
        gulp.dest(
          paths.join(
            paths.root,
            "node_modules/@types",
            getProjectSlug(cliPkg.name)
          )
        )
      )
  );
}

/**
 * Create JavaScript/TypeScript configuration base file in project's source
 */
function configureJsConfig() {
  const gulp = require("gulp");
  const template = require("gulp-template");
  const paths = require("../paths");
  const { coreLibrary } = require("../config");

  return (
    gulp
      .src(paths.join(paths.self.templates, "tsconfig.json"))
      // @ts-ignore
      .pipe(template({ coreLibrary, srcFolder: paths.frontend.src.folder }))
      .pipe(gulp.dest(paths.root))
  );
}

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

  return gulp.parallel(configureJsTypes, configureJsConfig)(callback);
};
