"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");
const ConfirmVote_1 = require("../protocol/ConfirmVote");
const ConfirmVoteBoundWithVote_1 = require("../protocol/ConfirmVoteBoundWithVote");
/**
 * This rule limits total absolute weight)of confirmed voteorders over given period of time.
 * It sums up absolute weights of upvotes and flags.
 */
class WeightForPeriodRule extends Rule_1.Rule {
    constructor(period, unit, weight) {
        super();
        this.rule = Rule_1.Rule.Type.WeightForPeriod;
        this.period = period;
        this.unit = unit;
        this.weight = weight;
    }
    type() {
        return Rule_1.Rule.Type.WeightForPeriod;
    }
    validate(voteorder, context, validationTimestamp = new Date() /* for unit testing */) {
        return __awaiter(this, void 0, void 0, function* () {
            this.validateRuleObject(this);
            const unitMultiplier = (this.unit === WeightForPeriodRule.PeriodUnit.DAY ? 24 * 60 * 60 :
                (this.unit === WeightForPeriodRule.PeriodUnit.HOUR ? 60 * 60 :
                    (this.unit === WeightForPeriodRule.PeriodUnit.MINUTE ? 60 :
                        1)));
            const numberOfSeconds = this.period * unitMultiplier;
            const until = new Date(validationTimestamp.getTime() - numberOfSeconds * 1000);
            const ops = yield context.getWiseOperations(context.getDelegatorUsername(), until);
            let sumOfWeightsForGivenPeriod = 0;
            ops.forEach(op => {
                if (ConfirmVote_1.ConfirmVote.isConfirmVote(op.command) && op.voter === context.getVoterUsername()) {
                    const confirmVoteOp = op.command;
                    // count only accepted vote confirmations:
                    if (confirmVoteOp.accepted && ConfirmVoteBoundWithVote_1.ConfirmVoteBoundWithVote.isConfirmVoteBoundWithVote(confirmVoteOp)) {
                        sumOfWeightsForGivenPeriod += Math.abs(confirmVoteOp.vote.weight);
                    }
                }
            });
            const totalSum = sumOfWeightsForGivenPeriod + Math.abs(voteorder.weight);
            if (totalSum > this.weight) {
                throw new ValidationException_1.ValidationException("WeightForPeriodRule: Sum of passed voteorders and the new voteorder (" + totalSum + ")"
                    + " was higher than allowed (" + this.weight + ") in a period of "
                    + this.period + " " + this.unit);
            }
        });
    }
    validateRuleObject(unprototypedObj) {
        ["period", "unit", "weight"].forEach(prop => {
            if (!_.has(unprototypedObj, prop))
                throw new ValidationException_1.ValidationException("WeightForPeriodRule: property " + prop + " is missing");
        });
        if (unprototypedObj.weight < 0)
            throw new ValidationException_1.ValidationException("WeightForPeriodRule: weight (" + unprototypedObj.weight + ") must be > 0 (the rule counts absolute VP of both upvotes and flags)");
        if (!_.includes([
            WeightForPeriodRule.PeriodUnit.DAY, WeightForPeriodRule.PeriodUnit.HOUR,
            WeightForPeriodRule.PeriodUnit.MINUTE, WeightForPeriodRule.PeriodUnit.SECOND
        ], unprototypedObj.unit))
            throw new ValidationException_1.ValidationException("WeightForPeriodRule: unknown unit " + unprototypedObj.unit);
    }
    getDescription() {
        return "You can use at most "
            + parseFloat((this.weight / 10000) + "").toFixed(3) + " full votes (or more partial votes) of this delegator over the period of " + this.period + " " + this.unit + "s";
    }
}
exports.WeightForPeriodRule = WeightForPeriodRule;
(function (WeightForPeriodRule) {
    let PeriodUnit;
    (function (PeriodUnit) {
        PeriodUnit["DAY"] = "day";
        PeriodUnit["HOUR"] = "hour";
        PeriodUnit["MINUTE"] = "minute";
        PeriodUnit["SECOND"] = "second";
    })(PeriodUnit = WeightForPeriodRule.PeriodUnit || (WeightForPeriodRule.PeriodUnit = {}));
})(WeightForPeriodRule = exports.WeightForPeriodRule || (exports.WeightForPeriodRule = {}));
//# sourceMappingURL=WeightForPeriodRule.js.map