"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.doLogin = void 0;
const Config_1 = require("../../modules/Config");
const Auth_1 = require("../../modules/Auth");
const winston = require("winston");
const R = require("ramda");
const inquirer = require("inquirer");
const I18n_1 = require("../../modules/I18n");
const validateEwizardInstance_1 = require("./validateEwizardInstance");
function doLogin(env = {}) {
    return __awaiter(this, void 0, void 0, function* () {
        const ewizardUrl = yield getEwizardInstance(env);
        const auth = new Auth_1.default({ ewizardUrl });
        const isLogenIn = yield auth.isTokenActive();
        return R.ifElse(R.not, () => submitLogin(auth, ewizardUrl, env), logInAlreadyLogged)(isLogenIn);
    });
}
exports.doLogin = doLogin;
function getEwizardInstance({ instance }) {
    return __awaiter(this, void 0, void 0, function* () {
        const config = yield Config_1.Config.get();
        const getUrl = R.path(['ewizard', 'url']);
        const getEwizardUrl = R.when(R.isNil, R.always(getUrl(config)));
        return R.compose(R.when(R.isNil, inquireEwizardUrl), getEwizardUrl)(instance);
    });
}
function inquireEwizardUrl() {
    const prompts = [{
            name: 'ewizardUrl',
            type: 'input',
            message: 'Ewizard instance:',
        }];
    return inquirer
        .prompt(prompts)
        .then((data) => (0, validateEwizardInstance_1.default)(data.ewizardUrl));
}
function submitLogin(auth, ewizardUrl, env) {
    return auth.login({
        ewizardUrl,
        username: env.user,
        password: env.password,
    })
        .then(logSuccess)
        .then(() => auth.ewizard);
}
function logSuccess() {
    winston.info(I18n_1.default.info('LOGIN_OK'));
}
function logInAlreadyLogged() {
    winston.info(I18n_1.default.info('LOGGED_IN_ALREADY'));
}
//# sourceMappingURL=login.js.map