/*
 * Copyright (C) 2022 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {openSync} from 'fontkit';
import config from '../icons.config.mjs';
import {existsSync} from 'fs';
import {getUsedIconsHtml, getUsedIconsTS} from './gather-used-icons.mjs';
import {fetchCodePointMap} from './get-code-points.mjs';

const commandName = '"npm run minify-icons"';
if (!existsSync(config.outputPath)) {
  console.error(`Minified font not found. Run ${commandName} first.`);
  process.exit(-1);
}

/** @type {import('fontkit').Font} */
const modifiedFont = openSync(config.outputPath);

let success = true;

// eslint-disable-next-line unicorn/prefer-top-level-await
checkAll().then(() => {
  console.log();
  if (success) {
    console.log('All icons are present in both fonts.');
  } else {
    console.error('Errors occurred.');
    process.exit(-1);
  }
});

/**
 *
 */
async function checkAll() {
  check(config.additionalIcons || {});
  check(await getUsedIconsTS(config.scriptGlob));
  check(await getUsedIconsHtml(config.htmlGlob));
}

/**
 * @param {Record<string, string[]>} icons
 */
async function check(icons) {
  const codePoints = await fetchCodePointMap();

  for (const icon of Object.values(icons).flat()) {
    const codePoint = codePoints.get(icon);
    if (!codePoint) throw new Error(`"${icon}" is not a valid icon`);
    if (!modifiedFont.getGlyph(Number.parseInt(codePoint, 16))) {
      throw new Error(`"${icon}" (code point ${codePoint}) is missing`);
    }
  }
}
