"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 listr2_1 = require("listr2");
const operators_1 = require("rxjs/operators");
const addSubslides_1 = require("../Api/scaffolding/addSubslides");
const I18n_1 = require("../modules/I18n");
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 subslide')
    .option('-s, --slide <slideId>', 'add subslide to the slide')
    .parse(process.argv);
subslide([...commander.args], commander)
    .catch(logger_1.handleError)
    .finally(logger_1.closeLogger);
function subslide(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();
        return createSubslides(slides, options);
    });
}
function createSubslides(slides, options) {
    return __awaiter(this, void 0, void 0, function* () {
        const addSubslidesAction = yield addSubslides_1.createAction(options.baseDirectory);
        const { slideGeneration$, structureGeneration$ } = yield addSubslidesAction(slides, options);
        yield validateSlide(options);
        const list = [...getSubslidesTasks(slides, slideGeneration$), ...getStructureTasks(structureGeneration$)];
        const tasks = new listr2_1.Listr(list, { exitOnError: false, concurrent: true });
        tasks.run({ slides: [] }).catch(_ => { });
    });
}
function getSubslidesTasks(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 validateSlide({ slide, baseDirectory }) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!slide) {
            throw new WizError_1.WizError('SLIDE_NOT_PROVIDED');
        }
        const structure = new Structure_1.default(baseDirectory);
        const slideData = yield structure.getSlideData(slide);
        if (slideData.type === 'archived') {
            throw new WizError_1.WizError('NO_SUBSLIDES_IN_ARCHIVED_SLIDE');
        }
        if (slideData.isSubslide) {
            throw new WizError_1.WizError('NO_SUBSLIDES_IN_SUBSLIDE_SLIDE');
        }
    });
}
//# sourceMappingURL=wiz-subslide.js.map