"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 types_1 = require("../../../../types");
const utils_1 = require("../../../../types/utils");
const utilsConversionModule = __importStar(require("../../../../utils/conversion"));
jest.mock('~/api/entities/Identity', require("../../../../testUtils/mocks/entities").mockIdentityModule('~/api/entities/Identity'));
jest.mock('~/api/entities/Instruction', require("../../../../testUtils/mocks/entities").mockInstructionModule('~/api/entities/Instruction'));
jest.mock('~/base/Procedure', require("../../../../testUtils/mocks/procedure").mockProcedureModule('~/base/Procedure'));
describe('Venue class', () => {
    let context;
    let venue;
    let id;
    let rawId;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        id = new bignumber_js_1.default(1);
        rawId = mocks_1.dsMockUtils.createMockU64(id.toNumber());
    });
    beforeEach(() => {
        context = mocks_1.dsMockUtils.getContextInstance();
        venue = new internal_1.Venue({ id }, context);
    });
    afterEach(() => {
        mocks_1.dsMockUtils.reset();
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.dsMockUtils.cleanup();
        mocks_1.entityMockUtils.cleanup();
        mocks_1.procedureMockUtils.cleanup();
    });
    test('should extend Entity', () => {
        expect(internal_1.Venue.prototype instanceof internal_1.Entity).toBe(true);
    });
    describe('method: isUniqueIdentifiers', () => {
        test('should return true if the object conforms to the interface', () => {
            expect(internal_1.Venue.isUniqueIdentifiers({ id: new bignumber_js_1.default(1) })).toBe(true);
            expect(internal_1.Venue.isUniqueIdentifiers({})).toBe(false);
            expect(internal_1.Venue.isUniqueIdentifiers({ id: 3 })).toBe(false);
        });
    });
    describe('method: exists', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should return whether if the venue exists or not', () => __awaiter(void 0, void 0, void 0, function* () {
            const owner = 'someDid';
            mocks_1.entityMockUtils.configureMocks({ identityOptions: { did: owner } });
            sinon_1.default.stub(utilsConversionModule, 'numberToU64').withArgs(id, context).returns(rawId);
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'venueInfo')
                .withArgs(rawId)
                .resolves(mocks_1.dsMockUtils.createMockOption());
            const result = yield venue.exists();
            expect(result).toEqual(false);
        }));
    });
    describe('method: details', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test("should throw an error if the venue doesn't exist", () => {
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'venueInfo')
                .resolves(mocks_1.dsMockUtils.createMockOption());
            mocks_1.dsMockUtils.createQueryStub('settlement', 'details');
            mocks_1.entityMockUtils.configureMocks({
                numberedPortfolioOptions: {
                    exists: false,
                },
            });
            return expect(venue.details()).rejects.toThrow("The Venue doesn't exist");
        });
        test('should return the Venue details', () => __awaiter(void 0, void 0, void 0, function* () {
            const description = 'someDescription';
            const type = types_1.VenueType.Other;
            const owner = 'someDid';
            mocks_1.entityMockUtils.configureMocks({ identityOptions: { did: owner } });
            sinon_1.default.stub(utilsConversionModule, 'numberToU64').withArgs(id, context).returns(rawId);
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'venueInfo')
                .withArgs(rawId)
                .resolves(mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockVenue({
                creator: mocks_1.dsMockUtils.createMockIdentityId(owner),
                // eslint-disable-next-line @typescript-eslint/naming-convention
                venue_type: mocks_1.dsMockUtils.createMockVenueType(type),
            })));
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'details')
                .withArgs(rawId)
                .resolves(mocks_1.dsMockUtils.createMockVenueDetails(description));
            const result = yield venue.details();
            expect(result).toEqual({
                owner: mocks_1.entityMockUtils.getIdentityInstance(),
                description,
                type,
            });
        }));
    });
    describe('method: getInstructions', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test("should throw an error if the Venue doesn't exist", () => {
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'venueInfo')
                .resolves(mocks_1.dsMockUtils.createMockOption());
            mocks_1.entityMockUtils.configureMocks({
                numberedPortfolioOptions: {
                    exists: false,
                },
            });
            return expect(venue.getInstructions()).rejects.toThrow("The Venue doesn't exist");
        });
        test("should return the Venue's pending and failed instructions", () => __awaiter(void 0, void 0, void 0, function* () {
            const id1 = new bignumber_js_1.default(1);
            const id2 = new bignumber_js_1.default(2);
            const detailsStub = mocks_1.entityMockUtils.getInstructionDetailsStub();
            sinon_1.default.stub(utilsConversionModule, 'numberToU64').withArgs(id, context).returns(rawId);
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'venueInfo')
                .resolves(mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockVenue()));
            mocks_1.dsMockUtils.createQueryStub('settlement', 'venueInstructions', {
                entries: [
                    [utils_1.tuple(rawId, mocks_1.dsMockUtils.createMockU64(id1.toNumber())), []],
                    [utils_1.tuple(rawId, mocks_1.dsMockUtils.createMockU64(id2.toNumber())), []],
                    [utils_1.tuple(rawId, mocks_1.dsMockUtils.createMockU64(3)), []],
                ],
            });
            detailsStub.onFirstCall().resolves({
                status: types_1.InstructionStatus.Pending,
            });
            detailsStub.onSecondCall().resolves({
                status: types_1.InstructionStatus.Failed,
            });
            detailsStub.onThirdCall().resolves({
                status: types_1.InstructionStatus.Executed,
            });
            const result = yield venue.getInstructions();
            expect(result.pending[0].id).toEqual(id1);
            expect(result.failed[0].id).toEqual(id2);
            expect(result.pending).toHaveLength(1);
            expect(result.failed).toHaveLength(1);
        }));
    });
    describe('method: getPendingInstructions', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test("should throw an error if the venue doesn't exist", () => {
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'venueInfo')
                .resolves(mocks_1.dsMockUtils.createMockOption());
            mocks_1.entityMockUtils.configureMocks({
                numberedPortfolioOptions: {
                    exists: false,
                },
            });
            return expect(venue.getPendingInstructions()).rejects.toThrow("The Venue doesn't exist");
        });
        test("should return the Venue's pending instructions", () => __awaiter(void 0, void 0, void 0, function* () {
            const instructionId = new bignumber_js_1.default(1);
            mocks_1.entityMockUtils.configureMocks({
                instructionOptions: { id: instructionId, isPending: true },
            });
            sinon_1.default.stub(utilsConversionModule, 'numberToU64').withArgs(id, context).returns(rawId);
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'venueInfo')
                .resolves(mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockVenue()));
            mocks_1.dsMockUtils.createQueryStub('settlement', 'venueInstructions', {
                entries: [[utils_1.tuple(rawId, mocks_1.dsMockUtils.createMockU64(instructionId.toNumber())), []]],
            });
            let result = yield venue.getPendingInstructions();
            expect(result[0].id).toEqual(instructionId);
            mocks_1.entityMockUtils.configureMocks({
                instructionOptions: {
                    id: instructionId,
                    exists: true,
                    details: {
                        status: types_1.InstructionStatus.Failed,
                    },
                },
            });
            result = yield venue.getPendingInstructions();
            expect(result.length).toBe(0);
        }));
    });
    describe('method: addInstruction', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should prepare the procedure and return the resulting transaction queue', () => __awaiter(void 0, void 0, void 0, function* () {
            const legs = [
                {
                    from: 'someDid',
                    to: 'anotherDid',
                    amount: new bignumber_js_1.default(1000),
                    token: 'SOME_TOKEN',
                },
                {
                    from: 'anotherDid',
                    to: 'aThirdDid',
                    amount: new bignumber_js_1.default(100),
                    token: 'ANOTHER_TOKEN',
                },
            ];
            const tradeDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
            const endBlock = new bignumber_js_1.default(10000);
            const expectedQueue = 'someQueue';
            mocks_1.procedureMockUtils
                .getPrepareStub()
                .withArgs({
                args: { instructions: [{ legs, tradeDate, endBlock }], venueId: id },
                transformer: internal_1.addInstructionTransformer,
            }, context)
                .resolves(expectedQueue);
            const queue = yield venue.addInstruction({ legs, tradeDate, endBlock });
            expect(queue).toBe(expectedQueue);
        }));
    });
    describe('method: addInstructions', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should prepare the procedure and return the resulting transaction queue', () => __awaiter(void 0, void 0, void 0, function* () {
            const legs = [
                {
                    from: 'someDid',
                    to: 'anotherDid',
                    amount: new bignumber_js_1.default(1000),
                    token: 'SOME_TOKEN',
                },
                {
                    from: 'anotherDid',
                    to: 'aThirdDid',
                    amount: new bignumber_js_1.default(100),
                    token: 'ANOTHER_TOKEN',
                },
            ];
            const tradeDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
            const endBlock = new bignumber_js_1.default(10000);
            const instructions = [
                {
                    legs,
                    tradeDate,
                    endBlock,
                },
            ];
            const expectedQueue = 'someQueue';
            mocks_1.procedureMockUtils
                .getPrepareStub()
                .withArgs({
                args: { venueId: id, instructions },
                transformer: undefined,
            }, context)
                .resolves(expectedQueue);
            const queue = yield venue.addInstructions({ instructions });
            expect(queue).toBe(expectedQueue);
        }));
    });
    describe('method: modify', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should prepare the procedure and return the resulting transaction queue', () => __awaiter(void 0, void 0, void 0, function* () {
            const expectedQueue = 'someQueue';
            const description = 'someDetails';
            const type = types_1.VenueType.Other;
            mocks_1.procedureMockUtils
                .getPrepareStub()
                .withArgs({
                args: { venueId: id, description, type },
                transformer: undefined,
            }, context)
                .resolves(expectedQueue);
            const queue = yield venue.modify({ description, type });
            expect(queue).toBe(expectedQueue);
        }));
    });
    describe('method: toJson', () => {
        test('should return a human readable version of the entity', () => {
            const token = new internal_1.Venue({ id: new bignumber_js_1.default(1) }, context);
            expect(token.toJson()).toBe('1');
        });
    });
});
describe('addInstructionTransformer', () => {
    test('should return a single Instruction', () => {
        const id = new bignumber_js_1.default(1);
        const result = internal_1.addInstructionTransformer([mocks_1.entityMockUtils.getInstructionInstance({ id })]);
        expect(result.id).toEqual(id);
    });
});
//# sourceMappingURL=index.js.map