"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 _ = require("lodash");
const ValidationException_1 = require("../validation/ValidationException");
const Rule_1 = require("./Rule");
class AuthorsRule extends Rule_1.Rule {
    constructor(mode, authors) {
        super();
        this.rule = Rule_1.Rule.Type.Authors;
        this.mode = mode;
        this.authors = authors;
    }
    type() {
        return Rule_1.Rule.Type.Authors;
    }
    validate(voteorder, context) {
        return __awaiter(this, void 0, void 0, function* () {
            this.validateRuleObject(this);
            let post;
            try {
                post = yield context.getPost();
            }
            catch (e) {
                if (e.notFoundException)
                    throw new ValidationException_1.ValidationException(e.message);
                else
                    throw e;
            }
            const authorIsOnList = (this.authors.indexOf(post.author) !== -1);
            if (this.mode == AuthorsRule.Mode.ALLOW) {
                if (!authorIsOnList)
                    throw new ValidationException_1.ValidationException("Author of the post is not on the allow list.");
            }
            else {
                if (authorIsOnList)
                    throw new ValidationException_1.ValidationException("Author of the post is on the deny list.");
            }
        });
    }
    validateRuleObject(unprototypedObj) {
        ["authors", "mode"].forEach(prop => {
            if (!_.has(unprototypedObj, prop))
                throw new ValidationException_1.ValidationException("AuthorsRule: property " + prop + " is missing");
        });
        if (!_.includes([AuthorsRule.Mode.ALLOW, AuthorsRule.Mode.DENY], unprototypedObj.mode))
            throw new ValidationException_1.ValidationException("AuthorsRule: unknown mode " + unprototypedObj.mode);
    }
    getDescription() {
        return (this.mode === "allow" ? "Allowed" : "Denied")
            + " " + _.join(this.authors, ", ");
    }
}
exports.AuthorsRule = AuthorsRule;
(function (AuthorsRule) {
    let Mode;
    (function (Mode) {
        Mode["ALLOW"] = "allow";
        Mode["DENY"] = "deny";
    })(Mode = AuthorsRule.Mode || (AuthorsRule.Mode = {}));
})(AuthorsRule = exports.AuthorsRule || (exports.AuthorsRule = {}));
//# sourceMappingURL=AuthorsRule.js.map