"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const async = require("async");
const inquirer = require("inquirer");
const eval_1 = require("./eval");
const ramda_1 = require("ramda");
const promptMapping = {
    string: 'input',
    boolean: 'confirm',
};
function ask(prompts, options, data, done) {
    async.eachSeries(Object.keys(prompts), (key, next) => {
        prompt(data, options, key, prompts[key], next);
    }, done);
}
exports.default = ask;
function prompt(data, options, key, prompt, done) {
    if (prompt.when && !eval_1.default(prompt.when, data)) {
        return done();
    }
    let promptDefault = prompt.default;
    if (typeof prompt.default === 'function') {
        promptDefault = function () {
            return prompt.default.bind(this)(data);
        };
    }
    if (options.default) {
        if (!ramda_1.hasPath(['answers', key], options)) {
            return setAnswers(data, key, done)({
                [key]: getDefault(promptDefault),
            });
        }
        return setAnswers(data, key, done)(options.answers);
    }
    inquirer.prompt([{
            type: promptMapping[prompt.type] || prompt.type,
            name: key,
            message: prompt.message || prompt.label || key,
            default: promptDefault,
            choices: prompt.choices || [],
            validate: prompt.validate || (() => true),
        }])
        .then(setAnswers(data, key, done))
        .catch(done);
}
function setAnswers(data, key, done) {
    return (answers) => {
        if (Array.isArray(answers[key])) {
            data[key] = {};
            answers[key].forEach((multiChoiceAnswer) => {
                data[key][multiChoiceAnswer] = true;
            });
        }
        else if (typeof answers[key] === 'string') {
            data[key] = answers[key].replace(/"/g, '\\"');
        }
        else {
            data[key] = answers[key];
        }
        done();
    };
}
function getDefault(defaultData) {
    if (typeof defaultData === 'function') {
        return defaultData();
    }
    return defaultData;
}
//# sourceMappingURL=ask.js.map