"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 sinon_1 = __importDefault(require("sinon"));
const internal_1 = require("../../../internal");
const mocks_1 = require("../../../testUtils/mocks");
const utils_1 = require("../../../types/utils");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
const utilsInternalModule = __importStar(require("../../../utils/internal"));
jest.mock('~/api/entities/Identity', require("../../../testUtils/mocks/entities").mockIdentityModule('~/api/entities/Identity'));
jest.mock('~/api/entities/SecurityToken', require("../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
describe('Checkpoint class', () => {
    let context;
    let id;
    let ticker;
    let balanceToBigNumberStub;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        id = new bignumber_js_1.default(1);
        ticker = 'SOME_TICKER';
        balanceToBigNumberStub = sinon_1.default.stub(utilsConversionModule, 'balanceToBigNumber');
    });
    beforeEach(() => {
        context = mocks_1.dsMockUtils.getContextInstance();
    });
    afterEach(() => {
        mocks_1.dsMockUtils.reset();
        mocks_1.entityMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.dsMockUtils.cleanup();
        mocks_1.entityMockUtils.cleanup();
    });
    test('should extend Entity', () => {
        expect(internal_1.Checkpoint.prototype instanceof internal_1.Entity).toBe(true);
    });
    describe('constructor', () => {
        test('should assign ticker and id to instance', () => {
            const checkpoint = new internal_1.Checkpoint({ id, ticker }, context);
            expect(checkpoint.token.ticker).toBe(ticker);
            expect(checkpoint.id).toEqual(id);
        });
    });
    describe('method: isUniqueIdentifiers', () => {
        test('should return true if the object conforms to the interface', () => {
            expect(internal_1.Checkpoint.isUniqueIdentifiers({ id: new bignumber_js_1.default(1), ticker: 'symbol' })).toBe(true);
            expect(internal_1.Checkpoint.isUniqueIdentifiers({})).toBe(false);
            expect(internal_1.Checkpoint.isUniqueIdentifiers({ id: new bignumber_js_1.default(1) })).toBe(false);
            expect(internal_1.Checkpoint.isUniqueIdentifiers({ id: 'id' })).toBe(false);
        });
    });
    describe('method: createdAt', () => {
        test("should return the Checkpoint's creation date", () => __awaiter(void 0, void 0, void 0, function* () {
            const checkpoint = new internal_1.Checkpoint({ id, ticker }, context);
            const timestamp = 12000;
            mocks_1.dsMockUtils.createQueryStub('checkpoint', 'timestamps', {
                returnValue: mocks_1.dsMockUtils.createMockMoment(timestamp),
            });
            const result = yield checkpoint.createdAt();
            expect(result).toEqual(new Date(timestamp));
        }));
    });
    describe('method: totalSupply', () => {
        test("should return the Checkpoint's total supply", () => __awaiter(void 0, void 0, void 0, function* () {
            const checkpoint = new internal_1.Checkpoint({ id, ticker }, context);
            const balance = 10000000000;
            const expected = new bignumber_js_1.default(balance).shiftedBy(-6);
            mocks_1.dsMockUtils.createQueryStub('checkpoint', 'totalSupply', {
                returnValue: mocks_1.dsMockUtils.createMockBalance(balance),
            });
            balanceToBigNumberStub.returns(expected);
            const result = yield checkpoint.totalSupply();
            expect(result).toEqual(expected);
        }));
    });
    describe('method: allBalances', () => {
        let stringToIdentityIdStub;
        beforeAll(() => {
            stringToIdentityIdStub = sinon_1.default.stub(utilsConversionModule, 'stringToIdentityId');
        });
        test("should return the Checkpoint's tokenholder balances", () => __awaiter(void 0, void 0, void 0, function* () {
            const checkpoint = new internal_1.Checkpoint({ id, ticker }, context);
            const balanceOf = [
                {
                    identity: 'did',
                    balance: new bignumber_js_1.default(100),
                },
                {
                    identity: 'did2',
                    balance: new bignumber_js_1.default(200),
                },
                {
                    identity: 'did3',
                    balance: new bignumber_js_1.default(10),
                },
            ];
            const rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
            const rawBalanceOf = balanceOf.map(({ identity, balance }) => ({
                identityId: mocks_1.dsMockUtils.createMockIdentityId(identity),
                balance: mocks_1.dsMockUtils.createMockBalance(balance.toNumber()),
            }));
            rawBalanceOf.forEach(({ identityId, balance: rawBalance }, index) => {
                const { identity, balance } = balanceOf[index];
                balanceToBigNumberStub.withArgs(rawBalance).returns(balance);
                stringToIdentityIdStub.withArgs(identity).returns(identityId);
            });
            const balanceOfEntries = rawBalanceOf.map(({ identityId, balance }) => utils_1.tuple({ args: [rawTicker, identityId] }, balance));
            mocks_1.dsMockUtils.createQueryStub('asset', 'balanceOf');
            sinon_1.default
                .stub(utilsInternalModule, 'requestPaginated')
                .resolves({ entries: balanceOfEntries, lastKey: null });
            mocks_1.dsMockUtils.createQueryStub('checkpoint', 'balanceUpdates', {
                multi: [
                    [mocks_1.dsMockUtils.createMockU64(1), mocks_1.dsMockUtils.createMockU64(2)],
                    [mocks_1.dsMockUtils.createMockU64(2)],
                    [],
                ],
            });
            const balanceMulti = [new bignumber_js_1.default(10000), new bignumber_js_1.default(20000)];
            const rawBalanceMulti = balanceMulti.map(balance => mocks_1.dsMockUtils.createMockBalance(balance.toNumber()));
            mocks_1.dsMockUtils.createQueryStub('checkpoint', 'balance', {
                multi: rawBalanceMulti,
            });
            rawBalanceMulti.forEach((rawBlance, index) => {
                balanceToBigNumberStub.withArgs(rawBlance).returns(balanceMulti[index]);
            });
            const { data } = yield checkpoint.allBalances();
            expect(data[0].identity.did).toEqual(balanceOf[0].identity);
            expect(data[1].identity.did).toEqual(balanceOf[1].identity);
            expect(data[2].identity.did).toEqual(balanceOf[2].identity);
            expect(data[0].balance).toEqual(balanceMulti[0]);
            expect(data[1].balance).toEqual(balanceMulti[1]);
            expect(data[2].balance).toEqual(balanceOf[2].balance);
        }));
    });
    describe('method: balance', () => {
        test("should return a specific Identity's balance at the Checkpoint", () => __awaiter(void 0, void 0, void 0, function* () {
            const checkpoint = new internal_1.Checkpoint({ id, ticker }, context);
            const balance = 10000000000;
            const expected = new bignumber_js_1.default(balance).shiftedBy(-6);
            balanceToBigNumberStub.returns(expected);
            mocks_1.dsMockUtils.createQueryStub('checkpoint', 'balanceUpdates', {
                returnValue: [
                    mocks_1.dsMockUtils.createMockU64(1),
                    mocks_1.dsMockUtils.createMockU64(2),
                    mocks_1.dsMockUtils.createMockU64(5),
                ],
            });
            mocks_1.dsMockUtils.createQueryStub('checkpoint', 'balance', {
                returnValue: mocks_1.dsMockUtils.createMockBalance(balance),
            });
            let result = yield checkpoint.balance({ identity: 'someDid' });
            expect(result).toEqual(expected);
            result = yield checkpoint.balance();
            expect(result).toEqual(expected);
            mocks_1.dsMockUtils.createQueryStub('checkpoint', 'balanceUpdates', {
                returnValue: [],
            });
            const tokenBalance = new bignumber_js_1.default(10);
            mocks_1.entityMockUtils.configureMocks({
                identityOptions: {
                    getTokenBalance: tokenBalance,
                },
            });
            result = yield checkpoint.balance();
            expect(result).toEqual(tokenBalance);
        }));
    });
    describe('method: exists', () => {
        test('should return whether the checkpoint exists', () => __awaiter(void 0, void 0, void 0, function* () {
            sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
            const checkpoint = new internal_1.Checkpoint({ id, ticker }, context);
            mocks_1.dsMockUtils.createQueryStub('checkpoint', 'checkpointIdSequence', {
                returnValue: [mocks_1.dsMockUtils.createMockU64(5)],
            });
            let result = yield checkpoint.exists();
            expect(result).toBe(true);
            mocks_1.dsMockUtils.createQueryStub('checkpoint', 'checkpointIdSequence', {
                returnValue: [mocks_1.dsMockUtils.createMockU64(0)],
            });
            result = yield checkpoint.exists();
            expect(result).toBe(false);
        }));
    });
    describe('method: toJson', () => {
        test('should return a human readable version of the entity', () => {
            const checkpoint = new internal_1.Checkpoint({ id: new bignumber_js_1.default(1), ticker: 'SOME_TICKER' }, context);
            expect(checkpoint.toJson()).toEqual({
                id: '1',
                ticker: 'SOME_TICKER',
            });
        });
    });
});
//# sourceMappingURL=Checkpoint.js.map