"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const types_1 = require("../../../polkadot/types");
const sinon_1 = __importDefault(require("sinon"));
const createCheckpointSchedule_1 = require("../createCheckpointSchedule");
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
const utilsInternalModule = __importStar(require("../../../utils/internal"));
jest.mock('~/api/entities/CheckpointSchedule', require("../../../testUtils/mocks/entities").mockCheckpointScheduleModule('~/api/entities/CheckpointSchedule'));
jest.mock('~/api/entities/SecurityToken', require("../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
describe('createCheckpointSchedule procedure', () => {
    let mockContext;
    let stringToTickerStub;
    let scheduleSpecToMeshScheduleSpecStub;
    let ticker;
    let rawTicker;
    let schedule;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        scheduleSpecToMeshScheduleSpecStub = sinon_1.default.stub(utilsConversionModule, 'scheduleSpecToMeshScheduleSpec');
        ticker = 'SOME_TICKER';
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        schedule = 'schedule';
    });
    let addTransactionStub;
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub().returns([schedule]);
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        stringToTickerStub.withArgs(ticker, mockContext).returns(rawTicker);
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.entityMockUtils.cleanup();
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should throw an error if the start date is in the past', () => {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        return expect(createCheckpointSchedule_1.prepareCreateCheckpointSchedule.call(proc, {
            ticker,
            start: new Date(new Date().getTime() - 10000),
            period: null,
            repetitions: null,
        })).rejects.toThrow('Schedule start date must be in the future');
    });
    test('should add a create checkpoint schedule transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const transaction = mocks_1.dsMockUtils.createTxStub('checkpoint', 'createSchedule');
        const start = new Date(new Date().getTime() + 10000);
        const period = {
            unit: types_2.CalendarUnit.Month,
            amount: 1,
        };
        const repetitions = 12;
        const rawSpec = mocks_1.dsMockUtils.createMockScheduleSpec({
            start: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(start.getTime())),
            period: mocks_1.dsMockUtils.createMockCalendarPeriod({
                unit: mocks_1.dsMockUtils.createMockCalendarUnit('Month'),
                amount: mocks_1.dsMockUtils.createMockU64(period.amount),
            }),
            remaining: mocks_1.dsMockUtils.createMockU32(repetitions),
        });
        scheduleSpecToMeshScheduleSpecStub
            .withArgs({ start, period, repetitions }, mockContext)
            .returns(rawSpec);
        const result = yield createCheckpointSchedule_1.prepareCreateCheckpointSchedule.call(proc, {
            ticker,
            start,
            period,
            repetitions,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, sinon_1.default.match({ resolvers: sinon_1.default.match.array }), rawTicker, rawSpec);
        expect(result).toBe(schedule);
    }));
    describe('createCheckpointScheduleResolver', () => {
        const filterEventRecordsStub = sinon_1.default.stub(utilsInternalModule, 'filterEventRecords');
        const id = new bignumber_js_1.default(1);
        const start = new Date('10/14/1987');
        const period = {
            unit: types_2.CalendarUnit.Month,
            amount: 1,
        };
        const remaining = 10;
        const at = new Date('10/10/2030');
        beforeAll(() => {
            mocks_1.entityMockUtils.initMocks({
                checkpointScheduleOptions: {
                    ticker,
                    id,
                    start,
                    period,
                    expiryDate: new Date(new Date().getTime() + 60 * 24 * 60 * 60 * 1000),
                },
            });
        });
        beforeEach(() => {
            filterEventRecordsStub.returns([
                mocks_1.dsMockUtils.createMockIEvent([
                    mocks_1.dsMockUtils.createMockIdentityId('someDid'),
                    mocks_1.dsMockUtils.createMockTicker(ticker),
                    mocks_1.dsMockUtils.createMockStoredSchedule({
                        id: mocks_1.dsMockUtils.createMockU64(id.toNumber()),
                        schedule: mocks_1.dsMockUtils.createMockCheckpointSchedule({
                            start: mocks_1.dsMockUtils.createMockMoment(start.getTime()),
                            period: mocks_1.dsMockUtils.createMockCalendarPeriod({
                                unit: mocks_1.dsMockUtils.createMockCalendarUnit('Month'),
                                amount: mocks_1.dsMockUtils.createMockU64(period.amount),
                            }),
                        }),
                        remaining: mocks_1.dsMockUtils.createMockU32(remaining),
                        at: mocks_1.dsMockUtils.createMockMoment(at.getTime()),
                    }),
                ]),
            ]);
        });
        afterEach(() => {
            filterEventRecordsStub.reset();
        });
        test('should return the new CheckpointSchedule', () => {
            const result = createCheckpointSchedule_1.createCheckpointScheduleResolver(ticker, mockContext)({});
            expect(result.token.ticker).toBe(ticker);
            expect(result.id).toEqual(id);
            expect(result.start).toEqual(start);
            expect(result.period).toEqual(period);
        });
    });
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = createCheckpointSchedule_1.getAuthorization.bind(proc);
            const start = new Date('10/14/1987');
            const period = {
                unit: types_2.CalendarUnit.Month,
                amount: 1,
            };
            const repetitions = 10;
            const token = mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker });
            expect(boundFunc({ ticker, start, period, repetitions })).toEqual({
                permissions: {
                    transactions: [types_1.TxTags.checkpoint.CreateSchedule],
                    tokens: [token],
                    portfolios: [],
                },
            });
        });
    });
});
//# sourceMappingURL=createCheckpointSchedule.js.map