"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 Assets_1 = require("../Assets");
const mocks_1 = require("../testUtils/mocks");
const types_1 = require("../types");
const utils_1 = require("../types/utils");
const utilsConversionModule = __importStar(require("../utils/conversion"));
jest.mock('~/api/entities/TickerReservation', require("../testUtils/mocks/entities").mockTickerReservationModule('~/api/entities/TickerReservation'));
jest.mock('~/base/Procedure', require("../testUtils/mocks/procedure").mockProcedureModule('~/base/Procedure'));
jest.mock('~/api/entities/Asset', require("../testUtils/mocks/entities").mockAssetModule('~/api/entities/Asset'));
describe('Assets Class', () => {
    let context;
    let assets;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
    });
    beforeEach(() => {
        context = mocks_1.dsMockUtils.getContextInstance();
        assets = new Assets_1.Assets(context);
    });
    afterEach(() => {
        mocks_1.dsMockUtils.reset();
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.dsMockUtils.cleanup();
        mocks_1.procedureMockUtils.cleanup();
    });
    describe('method: reserveTicker', () => {
        test('should prepare the procedure with the correct arguments and context, and return the resulting transaction queue', () => __awaiter(void 0, void 0, void 0, function* () {
            const args = {
                ticker: 'SOME_TICKER',
            };
            const expectedQueue = 'someQueue';
            mocks_1.procedureMockUtils
                .getPrepareStub()
                .withArgs({ args, transformer: undefined }, context)
                .resolves(expectedQueue);
            const queue = yield assets.reserveTicker(args);
            expect(queue).toBe(expectedQueue);
        }));
    });
    describe('method: createAsset', () => {
        test('should prepare the procedure with the correct arguments and context, and return the resulting transaction queue', () => __awaiter(void 0, void 0, void 0, function* () {
            const ticker = 'FAKE_TICKER';
            const args = {
                ticker,
                name: 'TEST',
                totalSupply: new bignumber_js_1.default(100),
                isDivisible: true,
                assetType: types_1.KnownAssetType.EquityCommon,
                securityIdentifier: [{ type: types_1.SecurityIdentifierType.Isin, value: '12345' }],
                fundingRound: 'Series A',
                requireInvestorUniqueness: false,
                reservationRequired: false,
            };
            const expectedQueue = 'someQueue';
            mocks_1.procedureMockUtils
                .getPrepareStub()
                .withArgs({ args, transformer: undefined }, context)
                .resolves(expectedQueue);
            const queue = yield assets.createAsset(args);
            expect(queue).toBe(expectedQueue);
        }));
    });
    describe('method: claimClassicTicker', () => {
        test('should prepare the procedure with the correct arguments and context, and return the resulting transaction queue', () => __awaiter(void 0, void 0, void 0, function* () {
            const args = {
                ticker: 'SOME_TICKER',
                ethereumSignature: 'someSig',
            };
            const expectedQueue = 'someQueue';
            mocks_1.procedureMockUtils
                .getPrepareStub()
                .withArgs({ args, transformer: undefined }, context)
                .resolves(expectedQueue);
            const queue = yield assets.claimClassicTicker(args);
            expect(queue).toBe(expectedQueue);
        }));
    });
    describe('method: isTickerAvailable', () => {
        afterEach(() => {
            mocks_1.entityMockUtils.reset();
        });
        test('should return true if ticker is available to reserve it', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.entityMockUtils.configureMocks({
                tickerReservationOptions: {
                    details: {
                        owner: mocks_1.entityMockUtils.getIdentityInstance(),
                        expiryDate: new Date(),
                        status: types_1.TickerReservationStatus.Free,
                    },
                },
            });
            const isTickerAvailable = yield assets.isTickerAvailable({ ticker: 'SOME_TICKER' });
            expect(isTickerAvailable).toBeTruthy();
        }));
        test('should return false if ticker is not available to reserve it', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.entityMockUtils.configureMocks({
                tickerReservationOptions: {
                    details: {
                        owner: mocks_1.entityMockUtils.getIdentityInstance(),
                        expiryDate: new Date(),
                        status: types_1.TickerReservationStatus.Reserved,
                    },
                },
            });
            const isTickerAvailable = yield assets.isTickerAvailable({ ticker: 'someTicker' });
            expect(isTickerAvailable).toBeFalsy();
        }));
        test('should allow subscription', () => __awaiter(void 0, void 0, void 0, function* () {
            const unsubCallback = 'unsubCallBack';
            mocks_1.entityMockUtils.configureMocks({
                tickerReservationOptions: {
                    details: (cbFunc) => __awaiter(void 0, void 0, void 0, function* () {
                        cbFunc({
                            owner: mocks_1.entityMockUtils.getIdentityInstance(),
                            expiryDate: new Date(),
                            status: types_1.TickerReservationStatus.Free,
                        });
                        return unsubCallback;
                    }),
                },
            });
            const callback = sinon_1.default.stub();
            const result = yield assets.isTickerAvailable({ ticker: 'someTicker' }, callback);
            expect(result).toBe(unsubCallback);
            sinon_1.default.assert.calledWithExactly(callback, true);
        }));
    });
    describe('method: getTickerReservations', () => {
        beforeAll(() => {
            sinon_1.default.stub(utilsConversionModule, 'signerValueToSignatory');
        });
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should return a list of ticker reservations if did parameter is set', () => __awaiter(void 0, void 0, void 0, function* () {
            const fakeTicker = 'TEST';
            const did = 'someDid';
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { withSeed: true } });
            mocks_1.dsMockUtils.createQueryStub('asset', 'assetOwnershipRelations', {
                entries: [
                    utils_1.tuple([mocks_1.dsMockUtils.createMockIdentityId(did), mocks_1.dsMockUtils.createMockTicker(fakeTicker)], mocks_1.dsMockUtils.createMockAssetOwnershipRelation('TickerOwned')),
                ],
            });
            const tickerReservations = yield assets.getTickerReservations({ owner: did });
            expect(tickerReservations).toHaveLength(1);
            expect(tickerReservations[0].ticker).toBe(fakeTicker);
        }));
        test('should return a list of ticker reservations owned by the Identity', () => __awaiter(void 0, void 0, void 0, function* () {
            const fakeTicker = 'TEST';
            const did = 'someDid';
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { withSeed: true } });
            mocks_1.dsMockUtils.createQueryStub('asset', 'assetOwnershipRelations', {
                entries: [
                    utils_1.tuple([mocks_1.dsMockUtils.createMockIdentityId(did), mocks_1.dsMockUtils.createMockTicker(fakeTicker)], mocks_1.dsMockUtils.createMockAssetOwnershipRelation('TickerOwned')),
                ],
            });
            const tickerReservations = yield assets.getTickerReservations();
            expect(tickerReservations).toHaveLength(1);
            expect(tickerReservations[0].ticker).toBe(fakeTicker);
        }));
        test('should filter out tickers with unreadable characters', () => __awaiter(void 0, void 0, void 0, function* () {
            const fakeTicker = 'TEST';
            const unreadableTicker = String.fromCharCode(65533);
            const did = 'someDid';
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { withSeed: true } });
            mocks_1.dsMockUtils.createQueryStub('asset', 'assetOwnershipRelations', {
                entries: [
                    utils_1.tuple([mocks_1.dsMockUtils.createMockIdentityId(did), mocks_1.dsMockUtils.createMockTicker(fakeTicker)], mocks_1.dsMockUtils.createMockAssetOwnershipRelation('TickerOwned')),
                    utils_1.tuple([mocks_1.dsMockUtils.createMockIdentityId(did), mocks_1.dsMockUtils.createMockTicker('someTicker')], mocks_1.dsMockUtils.createMockAssetOwnershipRelation('AssetOwned')),
                    utils_1.tuple([mocks_1.dsMockUtils.createMockIdentityId(did), mocks_1.dsMockUtils.createMockTicker(unreadableTicker)], mocks_1.dsMockUtils.createMockAssetOwnershipRelation('TickerOwned')),
                ],
            });
            const tickerReservations = yield assets.getTickerReservations();
            expect(tickerReservations).toHaveLength(1);
            expect(tickerReservations[0].ticker).toBe(fakeTicker);
        }));
    });
    describe('method: getTickerReservation', () => {
        test('should return a specific ticker reservation owned by the Identity', () => __awaiter(void 0, void 0, void 0, function* () {
            const ticker = 'TEST';
            const expiry = new Date();
            mocks_1.dsMockUtils.createQueryStub('asset', 'tickers', {
                returnValue: mocks_1.dsMockUtils.createMockTickerRegistration({
                    owner: mocks_1.dsMockUtils.createMockIdentityId('someDid'),
                    expiry: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(expiry.getTime()))),
                }),
            });
            const tickerReservation = yield assets.getTickerReservation({ ticker });
            expect(tickerReservation.ticker).toBe(ticker);
        }));
        test('should throw if ticker reservation does not exist', () => __awaiter(void 0, void 0, void 0, function* () {
            const ticker = 'TEST';
            mocks_1.dsMockUtils.createQueryStub('asset', 'tickers', {
                returnValue: mocks_1.dsMockUtils.createMockTickerRegistration({
                    owner: mocks_1.dsMockUtils.createMockIdentityId(),
                    expiry: mocks_1.dsMockUtils.createMockOption(),
                }),
            });
            return expect(assets.getTickerReservation({ ticker })).rejects.toThrow(`There is no reservation for ${ticker} ticker`);
        }));
        test('should throw if ticker is already an Asset', () => __awaiter(void 0, void 0, void 0, function* () {
            const ticker = 'TEST';
            mocks_1.dsMockUtils.createQueryStub('asset', 'tickers', {
                returnValue: mocks_1.dsMockUtils.createMockTickerRegistration({
                    owner: mocks_1.dsMockUtils.createMockIdentityId('someDid'),
                    expiry: mocks_1.dsMockUtils.createMockOption(),
                }),
            });
            return expect(assets.getTickerReservation({ ticker })).rejects.toThrow(`${ticker} Asset has been created`);
        }));
    });
    describe('method: getAsset', () => {
        test('should return a specific Asset', () => __awaiter(void 0, void 0, void 0, function* () {
            const ticker = 'TEST';
            const asset = yield assets.getAsset({ ticker });
            expect(asset.ticker).toBe(ticker);
        }));
        test('should throw if the Asset does not exist', () => __awaiter(void 0, void 0, void 0, function* () {
            const ticker = 'TEST';
            mocks_1.entityMockUtils.configureMocks({ assetOptions: { exists: false } });
            return expect(assets.getAsset({ ticker })).rejects.toThrow(`There is no Asset with ticker "${ticker}"`);
        }));
    });
    describe('method: getAssets', () => {
        beforeAll(() => {
            sinon_1.default.stub(utilsConversionModule, 'signerValueToSignatory');
        });
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should return a list of Assets owned by the supplied did', () => __awaiter(void 0, void 0, void 0, function* () {
            const fakeTicker = 'TEST';
            const did = 'someDid';
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { withSeed: true } });
            mocks_1.dsMockUtils.createQueryStub('asset', 'assetOwnershipRelations', {
                entries: [
                    utils_1.tuple([mocks_1.dsMockUtils.createMockIdentityId(did), mocks_1.dsMockUtils.createMockTicker(fakeTicker)], mocks_1.dsMockUtils.createMockAssetOwnershipRelation('AssetOwned')),
                ],
            });
            const asset = yield assets.getAssets({ owner: 'someDid' });
            expect(asset).toHaveLength(1);
            expect(asset[0].ticker).toBe(fakeTicker);
        }));
        test('should return a list of Assets owned by the current Identity if no did is supplied', () => __awaiter(void 0, void 0, void 0, function* () {
            const fakeTicker = 'TEST';
            const did = 'someDid';
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { withSeed: true } });
            mocks_1.dsMockUtils.createQueryStub('asset', 'assetOwnershipRelations', {
                entries: [
                    utils_1.tuple([mocks_1.dsMockUtils.createMockIdentityId(did), mocks_1.dsMockUtils.createMockTicker(fakeTicker)], mocks_1.dsMockUtils.createMockAssetOwnershipRelation('AssetOwned')),
                ],
            });
            const assetResults = yield assets.getAssets();
            expect(assetResults).toHaveLength(1);
            expect(assetResults[0].ticker).toBe(fakeTicker);
        }));
        test('should filter out Assets whose tickers have unreadable characters', () => __awaiter(void 0, void 0, void 0, function* () {
            const fakeTicker = 'TEST';
            const unreadableTicker = String.fromCharCode(65533);
            const did = 'someDid';
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { withSeed: true } });
            mocks_1.dsMockUtils.createQueryStub('asset', 'assetOwnershipRelations', {
                entries: [
                    utils_1.tuple([mocks_1.dsMockUtils.createMockIdentityId(did), mocks_1.dsMockUtils.createMockTicker(fakeTicker)], mocks_1.dsMockUtils.createMockAssetOwnershipRelation('AssetOwned')),
                    utils_1.tuple([mocks_1.dsMockUtils.createMockIdentityId(did), mocks_1.dsMockUtils.createMockTicker('someTicker')], mocks_1.dsMockUtils.createMockAssetOwnershipRelation('TickerOwned')),
                    utils_1.tuple([mocks_1.dsMockUtils.createMockIdentityId(did), mocks_1.dsMockUtils.createMockTicker(unreadableTicker)], mocks_1.dsMockUtils.createMockAssetOwnershipRelation('AssetOwned')),
                ],
            });
            const assetResults = yield assets.getAssets();
            expect(assetResults).toHaveLength(1);
            expect(assetResults[0].ticker).toBe(fakeTicker);
        }));
    });
});
//# sourceMappingURL=Assets.js.map