/*
 * 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 fontkit, {Font} from 'fontkit';
import config from '../icons.config';
import {existsSync} from 'fs';
import {getUsedIconsHtml, getUsedIconsTS} from './gather-used-icons';

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

let success = true;

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));
}

/**
 *
 */
function check(icons: Record<string, string[]>) {
  for (const [purpose, iconSet] of Object.entries(icons)) {
    for (const icon of iconSet) {
      if (!hasIcon(originalFont, icon)) {
        success = false;
        console.error(`${purpose}: ${icon} does not exist. Typo?`);
      } else if (!hasIcon(modifiedFont, icon)) {
        success = false;
        console.error(`${purpose}: ${icon} not found in minified font. Run ${commandName} to regenerate it.`);
      }
    }
  }
}

/**
 *
 */
function hasIcon(font: Font, icon: string) {
  return font.layout(icon).glyphs.some(it => it.isLigature);
}
