/* eslint-disable @typescript-eslint/no-require-imports */
const fs = require('fs');
const path = require('path');
const svgtofont = require('svgtofont');
const { createTypescript } = require('svgtofont/lib/utils');

const FONT_NAME = 'iconfont';
const FONT_CLASS_PREFIX = 'svg-icon';
const FONT_DIR_NAME = 'fonts';
const SVG_DIR_NAME = 'svg';
const STYLE_TEMPLATE_DIR_NAME = 'styles';

const cwdPath = process.cwd();
const svgPath = path.resolve(cwdPath, SVG_DIR_NAME);
const fontPath = path.resolve(cwdPath, FONT_DIR_NAME);
const styleTemplatePath = path.resolve(cwdPath, STYLE_TEMPLATE_DIR_NAME);

const generateIconFont = async () => {
  await svgtofont({
    src: svgPath,
    dist: fontPath,
    fontName: FONT_NAME,
    css: {
      include: /\.css$/,
    },
    styleTemplates: styleTemplatePath,
    classNamePrefix: FONT_CLASS_PREFIX,
    svgicons2svgfont: {
      fontHeight: 1000,
      normalize: true,
    },
    emptyDist: false,
    website: {
      version: '1.0.0',
    },
  });

  await createTypescript({
    src: svgPath,
    dist: fontPath,
    fontName: FONT_NAME,
    classNamePrefix: FONT_CLASS_PREFIX,
    typescript: {
      extension: 'ts',
    },
  });

  deleteUselessFiles();
  console.log('generate iconfont done!');
};

const deleteUselessFiles = () => {
  const keepFilesRegex = /^(iconfont\.(ts|css|woff)|index\.html)$/;

  fs.readdirSync(fontPath)
    .filter((file) => !keepFilesRegex.test(file))
    .forEach((file) => fs.unlinkSync(`${fontPath}/${file}`));
};

generateIconFont();
