"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const marked = require("marked");
const path = require("path");
const errors_1 = require("../errors");
const npm_1 = require("../npm");
const util_1 = require("../util");
/**
 * The publisher handle changing visility (public/private) of interactive controls.
 */
class Publisher {
    constructor(requester) {
        this.requester = requester;
    }
    /**
     * Unpublishes an interactive control version.
     */
    unpublish(name, version) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.requester.run(this.getPath(name, version), { method: 'DELETE' }).then((res) => __awaiter(this, void 0, void 0, function* () {
                if (res.status < 300) {
                    return;
                }
                throw new errors_1.PublishHttpError(res, yield res.text());
            }));
        });
    }
    /**
     * Publishes a package, making it accessible to everyone.
     */
    publish(project) {
        return __awaiter(this, void 0, void 0, function* () {
            const config = yield project.packageConfig();
            if (config.private) {
                throw new errors_1.PublishPrivateError();
            }
            const readme = yield this.renderReadme(project.baseDir());
            return this.requester
                .json('post', `${this.getPath(config.name, config.version)}/publish`, {
                readme,
                homepage: config.homepage || null,
                description: config.description || null,
                tags: config.keywords || [],
            })
                .then((res) => __awaiter(this, void 0, void 0, function* () {
                if (res.status < 300) {
                    return;
                }
                throw new errors_1.PublishHttpError(res, yield res.text());
            }));
        });
    }
    renderReadme(dir) {
        return __awaiter(this, void 0, void 0, function* () {
            const fname = yield npm_1.findReadme(dir);
            if (!fname) {
                return 'This project is missing a readme';
            }
            return marked(yield util_1.readFile(path.join(dir, fname)));
        });
    }
    getPath(name, version) {
        return `/interactive/bundles/${name}/versions/${version}`;
    }
}
exports.Publisher = Publisher;
