import gulp from "gulp"
import zip from "gulp-zip"
import { getPlanFromCli } from "../utils/readCliParams.js"
import {
  getBuildFolderPath,
  getReleaseFileName,
  getReleaseFolderPath,
  getReleasePath,
} from "../utils/paths.js"
import { getCurrentVersion } from "../utils/getVersion.js"
import path from "path"
import rename from "gulp-rename"

export const zipFilesTask = (plan, done) => {
  const version = getCurrentVersion()

  const buildPath = getBuildFolderPath(plan.slug)
  const base = buildPath.replace(/\/[^/]*$/, "")
  const releasePath = path.resolve(getReleaseFolderPath(plan.slug))

  return gulp
    .src(
      [
        buildPath + "/**",
        "!" + buildPath + "/.git",
        "!" + buildPath + "/.git/**",
        "!" + buildPath + "/.githooks/**",
        "!" + buildPath + "/dist/wp.mapsvg*",
        "!" + buildPath + "/.eslintignore",
        "!" + buildPath + "/.gitignore",
        "!" + buildPath + "/.prettierignore",
        "!" + buildPath + "/clockwork/**",
        "!" + buildPath + "/node_modules/**",
        "!" + buildPath + "/tests/**",
        "!" + buildPath + "/gulpfile.js",
      ],
      {
        base,
        encoding: false,
        allowEmpty: true,
      },
    )
    .pipe(
      rename((path) => {
        path.dirname = path.dirname.replace(/^[^/]+/, "mapsvg") // Replaces first directory component with "mapsvg"
      }),
    )
    .pipe(zip(getReleaseFileName({ version })))
    .pipe(gulp.dest(releasePath))
}

gulp.task("mapsvg_zip", function (done) {
  const plan = getPlanFromCli()
  return zipFilesTask(plan)
})
