"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 });
const commander = require("commander");
const inquirer_1 = require("inquirer");
const listr2_1 = require("listr2");
const operators_1 = require("rxjs/operators");
const addSlides_1 = require("../Api/scaffolding/addSlides");
const deleteSlides_1 = require("../Api/scaffolding/deleteSlides");
const I18n_1 = require("../modules/I18n");
const Logger_1 = require("../modules/Logger");
const Structure_1 = require("../modules/Structure");
const WizError_1 = require("../modules/WizError");
const ensureAuth_1 = require("./utils/ensureAuth");
const logger_1 = require("./utils/logger");
commander
    .name('wiz slide')
    .option('-c, --chapter <chapterId>', 'add slide to the chapter')
    .option('-d, --delete', 'delete slides from structure')
    .parse(process.argv);
slide([...commander.args], commander)
    .catch(logger_1.handleError)
    .finally(logger_1.closeLogger);
function slide(slides = [], command) {
    return __awaiter(this, void 0, void 0, function* () {
        const options = Object.assign(Object.assign({}, command.opts()), { baseDirectory: process.cwd() });
        yield ensureAuth_1.default();
        if (options.delete) {
            return deleteSlides(slides, options)
                .then(logSuccessDelete)
                .catch(logFailedDelete);
        }
        return createSlides(slides, options)
            .catch(err => Logger_1.default.error(err.message));
    });
}
function createChaperTask({ chapter, baseDirectory }) {
    return __awaiter(this, void 0, void 0, function* () {
        if (chapter) {
            const structure = new Structure_1.default(baseDirectory);
            const isChapterExists = yield structure.isChapterExists(chapter);
            if (!isChapterExists) {
                const { createChapter } = yield inquirer_1.prompt([{
                        name: 'createChapter',
                        type: 'confirm',
                        message: I18n_1.default.info('CHAPTER_NOT_EXISTS', chapter),
                        default: true,
                    }]);
                if (createChapter) {
                    return {
                        title: I18n_1.default.info('CHAPTER_GENERATING', chapter),
                        task: (ctx, task) => __awaiter(this, void 0, void 0, function* () {
                            yield structure.createChapter(chapter);
                            yield structure.save();
                        }),
                    };
                }
                throw new WizError_1.WizError('CHAPTER_NOT_EXISTS');
            }
        }
    });
}
function createSlides(slides, options) {
    return __awaiter(this, void 0, void 0, function* () {
        const addSlidesAction = yield addSlides_1.createAction(options.baseDirectory);
        const { slideGeneration$, structureGeneration$ } = yield addSlidesAction(slides, options);
        if (!options.chapter && slides.length) {
            Logger_1.default.info(I18n_1.default.info(slides.length === 1 ? 'CREATING_ARCHIVED_SLIDE' : 'CREATING_ARCHIVED_SLIDES'));
        }
        const list = [...getSlidesTasks(slides, slideGeneration$), ...getStructureTasks(structureGeneration$)];
        const chapterTask = yield createChaperTask(options);
        if (chapterTask) {
            list.unshift(chapterTask);
        }
        const tasks = new listr2_1.Listr(list, { exitOnError: false, concurrent: true });
        tasks.run({ slides: [] }).catch(_ => { });
    });
}
function getSlidesTasks(slides, slideGeneration$) {
    return slides.map((slideId) => {
        return {
            title: I18n_1.default.info('SLIDE_GENERATING', slideId),
            task: (ctx, task) => slideGeneration$.pipe(operators_1.filter(info => info.slide === slideId), operators_1.take(1)).toPromise().then((info) => {
                if (info.status === 'error') {
                    throw new Error(info.message);
                }
                ctx.slides.push(slideId);
            }).catch(err => {
                if (err.code === 'SLIDE_CREATION_IMPOSSIBLE') {
                    return task.skip();
                }
                throw err;
            }),
        };
    });
}
function getStructureTasks(obs$) {
    return [{
            title: 'Update structure',
            task: (ctx, task) => obs$.toPromise().then(() => {
                if (ctx.slides.length === 0) {
                    return task.skip('without changes');
                }
            }),
        }];
}
function deleteSlides(slides, options) {
    return __awaiter(this, void 0, void 0, function* () {
        const deleteSlideAction = yield deleteSlides_1.createAction(options.baseDirectory);
        return deleteSlideAction(slides, options);
    });
}
function logSuccessDelete(slides) {
    const message = slides.length > 1 ? I18n_1.default.info('SLIDES_DELETED') : I18n_1.default.info('SLIDE_DELETED');
    Logger_1.default.info(message);
}
function logFailedDelete(err) {
    Logger_1.default.error(I18n_1.default.error('SLIDE_DELETE_FAILED', err.message));
}
//# sourceMappingURL=wiz-slide.js.map