/**
 * Gulp tasks
 */

import fs from "fs";
import gulp from "gulp";
import replace from "gulp-replace";
import terser from "gulp-terser";
import cssnano from "gulp-cssnano";
import rename from "gulp-rename";

import locales from "./locales/index.ts";
import meta from "./package.json" assert { type: "json" };

gulp.task("copy:client:fonts", () =>
    gulp
        .src("./client/node_modules/three/examples/fonts/**/*")
        .pipe(gulp.dest("./built/_client_dist_/fonts/"))
);

gulp.task("copy:client:locales", (cb) => {
    fs.mkdirSync("./built/_client_dist_/locales", { recursive: true });

    const v = { _version_: meta.version };

    for (const [lang, locale] of Object.entries(locales)) {
        fs.writeFileSync(
            `./built/_client_dist_/locales/${lang}.${meta.version}.json`,
            JSON.stringify({ ...locale, ...v }),
            "utf-8"
        );
    }

    cb();
});

gulp.task("build:client:boot_script", () => {
    return gulp
        .src(["./assets-be/boot.template.js"])
        .pipe(replace("LANGS", JSON.stringify(Object.keys(locales))))
        .pipe(
            terser({
                toplevel: true,
            })
        )
        .pipe(rename("boot.js"))
        .pipe(gulp.dest("./assets-be/template"));
});

gulp.task("build:client:boot_style", () => {
    return gulp
        .src(["./assets-be/style.template.css"])
        .pipe(
            cssnano({
                zindex: false,
            })
        )
        .pipe(rename("style.css"))
        .pipe(gulp.dest("./assets-be/template"));
});

gulp.task("build:client:copy_twemoji", () => {
    return gulp
        .src(["node_modules/@discordapp/twemoji/dist/svg/*.svg"])
        .pipe(gulp.dest("./assets-be/twemoji"));
});

gulp.task(
    "build",
    gulp.parallel(
        "copy:client:locales",
        "copy:client:fonts",
        "build:client:boot_script",
        "build:client:boot_style",
        "build:client:copy_twemoji"
    )
);

gulp.task("default", gulp.task("build"));

gulp.task("watch", () => {
    gulp.watch(
        ["./packages/*/src/**/*"],
        { ignoreInitial: false },
        gulp.task("build")
    );
});
