"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 Rule_1 = require("./Rule");
const ValidationException_1 = require("../validation/ValidationException");
/**
 * This rule expires the ruleset.
 */
class ExpirationDateRule extends Rule_1.Rule {
    constructor(date) {
        super();
        this.rule = Rule_1.Rule.Type.ExpirationDate;
        this.date = date;
    }
    type() {
        return Rule_1.Rule.Type.ExpirationDate;
    }
    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 ruleDateParsed = new Date(Date.parse(this.date));
            const nowDate = new Date(Date.now());
            if (nowDate.getTime() > ruleDateParsed.getTime())
                throw new ValidationException_1.ValidationException("ExpirationDateRule: This rule has expired (expiration datetime was " + ruleDateParsed.toISOString()
                    + ", now is " + nowDate.toISOString() + ").");
        });
    }
    validateRuleObject(unprototypedObj) {
        ["date"].forEach(prop => {
            if (!_.has(unprototypedObj, prop))
                throw new ValidationException_1.ValidationException("ExpirationDateRule: property " + prop + " is missing");
        });
        if (!Date.parse(unprototypedObj.date))
            throw new ValidationException_1.ValidationException("ExpirationDateRule: date should be "
                + "formatted in one of the following formats: ISO 8601, IETF");
    }
    getDescription() {
        return "Ruleset expires at " + this.date;
    }
}
exports.ExpirationDateRule = ExpirationDateRule;
//# sourceMappingURL=ExpirationDateRule.js.map