#!/usr/bin/env node
var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};

// scripts/program.js
var require_program = __commonJS({
  "scripts/program.js"(exports, module2) {
    var { program } = require("commander");
    var startProgram2 = (name, description, options2, action2) => {
      program.name(name).description(description);
      for (const option of options2) {
        const short = (option.short?.startsWith("-") ? option.short : `-${option.short}`) || `-${option.name.charAt(0)}`;
        const long = option.long || `--${option.name} ${option.array ? "[" : "<"}${option.name}${option.array ? "s...]" : ">"}`;
        if (option.required) {
          program.requiredOption(
            `${short}, ${long}`,
            option.description || "",
            option.defaultValue
          );
        } else {
          program.option(
            `${short}, ${long}`,
            option.description || "",
            option.defaultValue
          );
        }
      }
      program.action(action2);
      program.parse();
    };
    module2.exports = { startProgram: startProgram2 };
  }
});

// scripts/clean-icons/index.js
var require_clean_icons = __commonJS({
  "scripts/clean-icons/index.js"(exports, module2) {
    var { globSync } = require("glob");
    var SVGFixer = require("oslllo-svg-fixer");
    var cleanIcons2 = async (src, ignoreGlobs, debug) => {
      const paths = `${src}/**/*.svg`;
      const options2 = {};
      if (ignoreGlobs) {
        options2.ignore = ignoreGlobs;
      }
      const globPaths = globSync(paths, options2).map((path) => path.replace(/\\/g, "/")).map((path) => path.slice(0, Math.max(0, path.lastIndexOf("/")))).filter((v, i, self) => i === self.indexOf(v));
      for (const path of globPaths) {
        await SVGFixer(path, path, { showProgressBar: debug }).fix();
      }
    };
    module2.exports = { cleanIcons: cleanIcons2 };
  }
});

// scripts/generate-icon-fonts/gather-icons.js
var require_gather_icons = __commonJS({
  "scripts/generate-icon-fonts/gather-icons.js"(exports, module2) {
    var FSE2 = require("fs-extra");
    var { globSync } = require("glob");
    var generalPrefix = "";
    var availableSizes = [16, 20, 24, 32, 48, 64];
    var componentSizes = [24, 20, 16];
    var allTemporaryDir = "all";
    var initTemporaryIconFiles = (globPaths, prefix, temporaryDirectory) => {
      const foundIconFiles = [];
      for (const svgPath of globPaths) {
        const paths = svgPath.split("/");
        let filename = paths.at(-1);
        let iconName;
        if (prefix) {
          filename = filename.replace(prefix, "");
        }
        iconName = filename.replace(".svg", "");
        for (const size of availableSizes) {
          iconName = iconName.replace(`_${size}`, "");
        }
        FSE2.copyFileSync(
          svgPath,
          `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}${filename}`
        );
        if (iconName && !foundIconFiles.includes(iconName)) {
          foundIconFiles.push(iconName);
        }
      }
      return foundIconFiles;
    };
    var initDefaultFile = (temporaryDirectory, iconFileName) => {
      const defaultFileExists = FSE2.existsSync(
        `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}${iconFileName}.svg`
      );
      if (!defaultFileExists) {
        for (const size of componentSizes) {
          const sizeFileName = `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}${iconFileName}_${size}.svg`;
          if (FSE2.existsSync(sizeFileName)) {
            FSE2.copyFileSync(
              sizeFileName,
              `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}${iconFileName}.svg`
            );
            break;
          }
        }
      }
    };
    var initComponentSizes = (temporaryDirectory, iconFileName) => {
      for (const size of componentSizes) {
        const requiredFilePath = `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}${iconFileName}_${size}.svg`;
        if (!FSE2.existsSync(requiredFilePath)) {
          const nextBestSizeArray = size === 16 ? [20, 24] : size === 20 ? [24, 16] : [20, 16];
          for (const nextSize of nextBestSizeArray) {
            const nextSizeFilePath = `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}${iconFileName}_${nextSize}.svg`;
            if (FSE2.existsSync(nextSizeFilePath)) {
              FSE2.copyFileSync(nextSizeFilePath, requiredFilePath);
              break;
            }
          }
        }
      }
    };
    var gatherIcons2 = (temporaryDirectory, values) => {
      const { src, ignoreGlobs, prefix, dryRun, variants, withSizes, debug } = values;
      const paths = `${src}/**/*.svg`;
      const splitSizesArray = withSizes ? ["", ...availableSizes] : [""];
      const splitVariantsArray = variants.length > 0 ? ["", ...variants] : [""];
      const globPaths = globSync(paths, { ignore: ignoreGlobs }).map(
        (path) => path.replace(/\\/g, "/")
      );
      if (dryRun) {
        console.log("files:", globPaths);
        return;
      }
      if (!FSE2.existsSync(temporaryDirectory)) {
        FSE2.mkdirSync(temporaryDirectory);
      }
      if (!FSE2.existsSync(`${temporaryDirectory}/${allTemporaryDir}`)) {
        FSE2.mkdirSync(`${temporaryDirectory}/${allTemporaryDir}`);
      }
      const foundIconFiles = initTemporaryIconFiles(
        globPaths,
        prefix,
        temporaryDirectory
      );
      if (debug) {
        console.log(`Found ${foundIconFiles.length} icons`);
      }
      for (const variant of splitVariantsArray) {
        for (const iconFileName of foundIconFiles.filter(
          (fileName) => !variants.some((va) => fileName.endsWith(`_${va}`))
        )) {
          const fileName = variant === "" ? iconFileName : `${iconFileName}_${variant}`;
          initDefaultFile(temporaryDirectory, fileName);
          initComponentSizes(temporaryDirectory, fileName);
          for (const size of splitSizesArray) {
            const sizeFileEnding = `${size === "" ? "" : `_${size}`}`;
            const directory = `${variant === "" ? "default" : variant}${sizeFileEnding}`;
            const defaultFilePath = `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}${fileName}.svg`;
            const sizeFilePath = `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}${fileName}${sizeFileEnding}.svg`;
            const fallbackFilePath = `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}${iconFileName}.svg`;
            const fallbackSizeFilePath = `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}${iconFileName}${sizeFileEnding}.svg`;
            const placeholderFilePath = `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}x_placeholder.svg`;
            const placeholderSizeFilePath = `${temporaryDirectory}/${allTemporaryDir}/${generalPrefix}x_placeholder${sizeFileEnding}.svg`;
            if (!FSE2.existsSync(`${temporaryDirectory}/${directory}`)) {
              FSE2.mkdirSync(`${temporaryDirectory}/${directory}`);
            }
            if (FSE2.existsSync(sizeFilePath)) {
              FSE2.copyFileSync(
                sizeFilePath,
                `${temporaryDirectory}/${directory}/${generalPrefix}${iconFileName}.svg`
              );
            } else if (FSE2.existsSync(defaultFilePath)) {
              FSE2.copyFileSync(
                defaultFilePath,
                `${temporaryDirectory}/${directory}/${generalPrefix}${iconFileName}.svg`
              );
            } else if (FSE2.existsSync(placeholderSizeFilePath)) {
              FSE2.copyFileSync(
                placeholderSizeFilePath,
                `${temporaryDirectory}/${directory}/${generalPrefix}${iconFileName}.svg`
              );
            } else if (FSE2.existsSync(placeholderFilePath)) {
              FSE2.copyFileSync(
                placeholderFilePath,
                `${temporaryDirectory}/${directory}/${generalPrefix}${iconFileName}.svg`
              );
            } else if (FSE2.existsSync(fallbackSizeFilePath)) {
              FSE2.copyFileSync(
                fallbackSizeFilePath,
                `${temporaryDirectory}/${directory}/${generalPrefix}${iconFileName}.svg`
              );
            } else {
              FSE2.copyFileSync(
                fallbackFilePath,
                `${temporaryDirectory}/${directory}/${generalPrefix}${iconFileName}.svg`
              );
            }
          }
        }
      }
    };
    module2.exports = { gatherIcons: gatherIcons2 };
  }
});

// scripts/generate-icon-fonts/svg-to-font.js
var require_svg_to_font = __commonJS({
  "scripts/generate-icon-fonts/svg-to-font.js"(exports, module2) {
    var path = require("node:path");
    var svgtofont = require("svgtofont");
    var svgToFont2 = async (temporaryDirectory, dist, values) => {
      const { fontName, debug } = values;
      const fileName = __filename;
      let lastSlashIndex = fileName.lastIndexOf("\\");
      if (lastSlashIndex === -1) {
        lastSlashIndex = fileName.lastIndexOf("/");
      }
      const generateIconFontsDir = fileName.slice(0, Math.max(0, lastSlashIndex));
      try {
        return svgtofont({
          src: temporaryDirectory,
          dist,
          fontName,
          log: debug,
          css: true,
          outSVGReact: false,
          // TODO: Consider if we want to give this to users
          outSVGPath: false,
          useNameAsUnicode: true,
          generateInfoData: true,
          // SvgoOptions: TODO: https://github.com/svg/svgo#configuration,
          svgicons2svgfont: {
            fontHeight: 1e3,
            normalize: true,
            centerHorizontally: true
          },
          website: {
            index: "font-class",
            template: path.resolve(
              generateIconFontsDir,
              "templates/template.ejs"
            )
          },
          styleTemplates: path.resolve(generateIconFontsDir, "styles")
        });
      } catch (error) {
        console.error(error);
      }
      return true;
    };
    module2.exports = { svgToFont: svgToFont2 };
  }
});

// scripts/generate-icon-fonts/index.js
var FSE = require("fs-extra");
var { startProgram } = require_program();
var { cleanIcons } = require_clean_icons();
var { gatherIcons } = require_gather_icons();
var { svgToFont } = require_svg_to_font();
var options = [
  {
    name: "ignoreGlobs",
    description: "Path icon glob to exclude from the fonts",
    array: true
  },
  {
    name: "variants",
    description: 'Font variants e.g. solid, inverted, etc. We always add a "default" variant for icons.',
    array: true,
    defaultValue: []
  },
  {
    name: "cleanIgnoreVariants",
    description: "Ignore variants which should not be cleaned automatically",
    array: true,
    defaultValue: []
  },
  {
    name: "withSizes",
    description: "Splits the font into different sizes"
  },
  {
    name: "src",
    description: "Src folder with all svgs",
    required: true
  },
  {
    name: "prefix",
    description: "Prefix of icons to delete for icons"
  },
  {
    name: "fontName",
    description: "The name of your font",
    required: true
  },
  {
    name: "dryRun",
    description: "prints the output of the command"
  },
  {
    name: "debug",
    description: "Extra logging",
    defaultValue: false
  }
];
var fileEndingsToDelete = [
  "eot",
  "less",
  "module.less",
  "styl",
  "svg",
  "symbol.svg",
  "ttf",
  "woff"
];
var debugLog = (debug, message) => {
  if (debug) {
    console.log(message);
  }
};
var action = async (string_, options2) => {
  const values = options2._optionValues;
  const { src, fontName, dryRun, cleanIgnoreVariants, debug } = values;
  const dist = `${src}/fonts`;
  const temporaryDirectory = `${src}/tmp`;
  const ignoreVariants = [...cleanIgnoreVariants].map(
    (igVar) => `**/${igVar}*/**`
  );
  if (dryRun) {
    console.log("values:", values);
    gatherIcons(temporaryDirectory, values);
  } else {
    if (FSE.existsSync(temporaryDirectory)) {
      FSE.removeSync(temporaryDirectory);
    }
    if (FSE.existsSync(dist)) {
      FSE.removeSync(dist);
    }
    debugLog(debug, "---Start gathering icon---");
    gatherIcons(temporaryDirectory, values);
    debugLog(debug, "---Start cleaning icon---");
    await cleanIcons(`${temporaryDirectory}/*`, ignoreVariants, debug);
    debugLog(debug, "---Start svg to font ---");
    const allTemporaryDirectories = FSE.readdirSync(temporaryDirectory);
    for (const directory of allTemporaryDirectories) {
      const subDist = `${dist}/${directory}`;
      const subTemporaryDir = `${temporaryDirectory}/${directory}`;
      debugLog(debug, `svgToFont for ${subTemporaryDir}`);
      await svgToFont(subTemporaryDir, subDist, values);
      for (const ending of fileEndingsToDelete) {
        FSE.removeSync(`${subDist}/${fontName}.${ending}`);
      }
      FSE.removeSync(`${subDist}/symbol.html`);
      FSE.removeSync(`${subDist}/unicode.html`);
    }
    if (!debug) {
      FSE.removeSync(temporaryDirectory);
    }
  }
};
startProgram(
  "@db-ui/foundations - generate fonts",
  "CLI to generate icon fonts for DB UX Design System",
  options,
  action
);
