import { difference, flatMap, includes, isEmpty, reject, some, uniq, values } from 'lodash-es';
import { Lexer } from 'chevrotain';
import TokenCollectorVisitor from './token-collector-visitor.js';
export function checkTokens(allDefinedTokens, rules) {
    const usedTokens = getUsedTokens(rules);
    const unusedTokens = getUselessTokens(usedTokens, allDefinedTokens);
    if (unusedTokens.length !== 0) {
        const unusedTokenTypeNames = unusedTokens.map(tokenType => tokenType.name);
        throw Error(`Unused token definitions found: [ ${unusedTokenTypeNames.join(', ')} ]`);
    }
}
function getUsedTokens(rules) {
    return rules.reduce((result, currentRule) => {
        const collector = new TokenCollectorVisitor();
        currentRule.accept(collector);
        return uniq(result.concat(collector.actualTokens));
    }, []);
}
function getUselessTokens(usedTokens, allDefinedTokens) {
    const usedCategories = uniq(flatMap(usedTokens, 'CATEGORIES'));
    const notDirectlyUsedTokens = difference(allDefinedTokens, uniq(usedTokens, usedCategories));
    const redundant = reject(notDirectlyUsedTokens, token => {
        const tokCategories = token.CATEGORIES;
        return some(tokCategories, category => includes(usedCategories, category));
    });
    return reject(redundant, tokenType => tokenType.GROUP === Lexer.SKIPPED);
}
export function checkConfigKeys(definedTokensMap, usedConfigKeys) {
    checkForUselessConfigurationKeys(definedTokensMap, usedConfigKeys);
    checkForMissingConfigurationKeys(definedTokensMap, usedConfigKeys);
}
function checkForUselessConfigurationKeys(definedTokensMap, usedConfigKeys) {
    const redundantConfigKeys = difference(usedConfigKeys, Object.keys(definedTokensMap));
    if (!isEmpty(redundantConfigKeys)) {
        throw Error(`Useless configuration keys: [ ${redundantConfigKeys.join(', ')} ]`);
    }
}
function checkForMissingConfigurationKeys(definedTokensMap, usedConfigKeys) {
    const definedConfigKeyNames = values(definedTokensMap)
        .filter(tokenType => includes(tokenType.CATEGORIES, definedTokensMap.CONFIG_KEY))
        .map(tokenType => tokenType.name);
    const missingConfigKeys = difference(definedConfigKeyNames, usedConfigKeys);
    if (!isEmpty(missingConfigKeys)) {
        throw Error(`Missing configuration keys: [ ${missingConfigKeys.join(', ')} ]`);
    }
}
