import chalk from 'chalk';
import { createLogger } from '@yeoman/adapter';
import createDebug from 'debug';
const addPrefixToParameters = (prefix, ...args) => {
    args[0] = `${prefix} ${args[0]}`;
    return args;
};
const formatWarningMessageHeader = (...args) => {
    return addPrefixToParameters(chalk.yellow.bold('WARNING!'), ...args);
};
const formatErrorMessageHeader = (...args) => {
    return addPrefixToParameters(chalk.red.bold('ERROR!'), ...args);
};
const formatFatalMessageHeader = (...args) => {
    return addPrefixToParameters(chalk.red.bold('FATAL!'), ...args);
};
const formatInfoMessageHeader = (...args) => {
    return addPrefixToParameters(chalk.green('INFO!'), ...args);
};
export const CLI_LOGGER = 'begcode:cli';
export const createJHipsterLogger = (options = {}) => {
    const { namespace = 'begcode' } = options;
    const debug = createDebug(namespace);
    const customJHipsterLogger = {
        debugger: debug,
        debug(msg, ...args) {
            this.debugger(msg, ...args);
        },
        warn(...args) {
            this.writeln(...formatWarningMessageHeader(...args));
            return this;
        },
        verboseInfo(...args) {
            this.writeln(...formatInfoMessageHeader(...args));
            return this;
        },
        log(...args) {
            this.writeln(...args);
            return this;
        },
        error(msg, error) {
            const errorMessage = formatErrorMessageHeader(msg);
            this.console.error(...errorMessage);
            if (error) {
                this.console.error(error);
            }
            process.exitCode = 1;
        },
        fatal(msg, trace) {
            const fatalMessage = formatFatalMessageHeader(msg);
            this.console.error(...fatalMessage);
            if (trace) {
                this.console.error(trace);
            }
            process.exit(1);
        },
    };
    const logger = createLogger({ ...options, loggers: customJHipsterLogger });
    const cliLogger = namespace === CLI_LOGGER;
    let debugEnabled = options.debugEnabled;
    if (cliLogger) {
        debugEnabled = debugEnabled || process.argv.includes('-d') || process.argv.includes('--debug');
        if (debugEnabled) {
            logger.verboseInfo('Debug logging is on');
        }
    }
    if (debugEnabled) {
        logger.debugger.enabled = true;
    }
    return logger;
};
