/* eslint no-console:0 */

// This is an internal Node tool, not part of the KaTeX distribution,
// whose purpose is to generate unicodeSymbols.js in this directory.
// In this way, only this tool, and not the distribution/browser,
// needs String's normalize function.
const path = require('path');
const fs = require('fs');

const target = path.join(__dirname, 'unicodeSymbols.js');
const targetMtime = fs.statSync(target).mtime;
if (fs.statSync(__filename).mtime <= targetMtime && fs.statSync(
        path.join(__dirname, 'unicodeAccents.js')).mtime <= targetMtime) {
    process.exit(0);
}

require('@babel/register');
const accents = require('./unicodeAccents').default;

const encode = function(string) {
    let output = '"';
    for (let i = 0; i < string.length; i++) {
        let hex = string.charCodeAt(i).toString(16);
        while (hex.length < 4) {
            hex = `0${hex}`;
        }
        output += `\\u${hex}`;
    }
    output = `${output}"`;
    return output;
};

let unicodeSymbols =
`// @flow
// This file is GENERATED by unicodeMake.js. DO NOT MODIFY.

export default {
`;

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +
    "αβγδεϵζηθϑικλμνξοπϖρϱςστυφϕχψωΓΔΘΛΞΠΣΥΦΨΩ";
for (const letter of letters) {
    for (const accent of Object.getOwnPropertyNames(accents)) {
        const combined = letter + accent;
        const normalized = combined.normalize('NFC');
        if (normalized.length === 1) {
            unicodeSymbols +=
                `    ${encode(normalized)}: ${encode(combined)},`
                + `  // ${normalized} = ${accents[accent].text}{${letter}}\n`;
        }
        for (const accent2 of Object.getOwnPropertyNames(accents)) {
            if (accent === accent2) {
                continue;
            }
            const combined2 = combined + accent2;
            const normalized2 = combined2.normalize('NFC');
            if (normalized2.length === 1) {
                unicodeSymbols +=
                    `    ${encode(normalized2)}: ${encode(combined2)},`
                    + `  // ${normalized2} = ${accents[accent].text}`
                    + `${accents[accent2].text}{${letter}}\n`;
            }
        }
    }
}

unicodeSymbols += `};
`;

fs.writeFileSync(target, unicodeSymbols);
