"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 reserveTicker_1 = require("../reserveTicker");
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/TickerReservation', require("../../../testUtils/mocks/entities").mockTickerReservationModule('~/api/entities/TickerReservation'));
describe('reserveTicker procedure', () => {
    let mockContext;
    let stringToTickerStub;
    let ticker;
    let rawTicker;
    let args;
    let reservation;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks({
            contextOptions: {
                balance: {
                    free: new bignumber_js_1.default(1000),
                    locked: new bignumber_js_1.default(0),
                    total: new bignumber_js_1.default(1000),
                },
            },
        });
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks({ identityOptions: { did: 'someOtherDid' } });
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        ticker = 'SOME_TICKER';
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        args = {
            ticker,
        };
        reservation = 'reservation';
    });
    let addTransactionStub;
    let transaction;
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub().returns([reservation]);
        mocks_1.entityMockUtils.getTickerReservationDetailsStub().resolves({
            owner: mocks_1.entityMockUtils.getIdentityInstance(),
            expiryDate: null,
            status: types_2.TickerReservationStatus.Free,
        });
        mocks_1.dsMockUtils.createQueryStub('asset', 'tickerConfig', {
            returnValue: mocks_1.dsMockUtils.createMockTickerRegistrationConfig(),
        });
        transaction = mocks_1.dsMockUtils.createTxStub('asset', 'registerTicker');
        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 ticker is already reserved', () => __awaiter(void 0, void 0, void 0, function* () {
        const expiryDate = new Date(new Date().getTime() + 1000);
        mocks_1.entityMockUtils.getTickerReservationDetailsStub().resolves({
            owner: mocks_1.entityMockUtils.getIdentityInstance(),
            expiryDate,
            status: types_2.TickerReservationStatus.Reserved,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let error;
        try {
            yield reserveTicker_1.prepareReserveTicker.call(proc, args);
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe(`Ticker "${ticker}" already reserved`);
        expect(error.data).toMatchObject({ expiryDate });
    }));
    test('should throw an error if the current reservation is permanent', () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.entityMockUtils.getTickerReservationDetailsStub().resolves({
            owner: mocks_1.entityMockUtils.getIdentityInstance(),
            expiryDate: null,
            status: types_2.TickerReservationStatus.Reserved,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let error;
        try {
            yield reserveTicker_1.prepareReserveTicker.call(proc, args);
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe(`Ticker "${ticker}" already reserved`);
        expect(error.data).toMatchObject({ expiryDate: null });
    }));
    test('should throw an error if an Asset with that ticker has already been launched', () => {
        mocks_1.entityMockUtils.getTickerReservationDetailsStub().resolves({
            owner: mocks_1.entityMockUtils.getIdentityInstance(),
            expiryDate: null,
            status: types_2.TickerReservationStatus.AssetCreated,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        return expect(reserveTicker_1.prepareReserveTicker.call(proc, args)).rejects.toThrow(`An Asset with ticker "${ticker}" already exists`);
    });
    test('should throw an error if extendPeriod property is set to true and the ticker has not been reserved or the reservation has expired', () => {
        const expiryDate = new Date(2019, 1, 1);
        mocks_1.entityMockUtils.getTickerReservationDetailsStub().resolves({
            owner: mocks_1.entityMockUtils.getIdentityInstance(),
            expiryDate,
            status: types_2.TickerReservationStatus.Free,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        return expect(reserveTicker_1.prepareReserveTicker.call(proc, Object.assign(Object.assign({}, args), { extendPeriod: true }))).rejects.toThrow('Ticker not reserved or the reservation has expired');
    });
    test('should add a register ticker transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let result = yield reserveTicker_1.prepareReserveTicker.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub, sinon_1.default.match({
            transaction,
            resolvers: sinon_1.default.match.array,
            args: [rawTicker],
        }));
        expect(result).toBe(reservation);
        mocks_1.entityMockUtils.getTickerReservationDetailsStub().resolves({
            owner: mocks_1.entityMockUtils.getIdentityInstance(),
            expiryDate: new Date(3000, 12, 12),
            status: types_2.TickerReservationStatus.Reserved,
        });
        result = yield reserveTicker_1.prepareReserveTicker.call(proc, Object.assign(Object.assign({}, args), { extendPeriod: true }));
        sinon_1.default.assert.calledWith(addTransactionStub, sinon_1.default.match({ transaction, resolvers: sinon_1.default.match.array, args: [rawTicker] }));
        expect(result).toBe(reservation);
    }));
});
describe('tickerReservationResolver', () => {
    const filterEventRecordsStub = sinon_1.default.stub(utilsInternalModule, 'filterEventRecords');
    const tickerString = 'someTicker';
    const ticker = mocks_1.dsMockUtils.createMockTicker(tickerString);
    beforeAll(() => {
        mocks_1.entityMockUtils.initMocks({ tickerReservationOptions: { ticker: tickerString } });
    });
    beforeEach(() => {
        filterEventRecordsStub.returns([mocks_1.dsMockUtils.createMockIEvent(['someDid', ticker])]);
    });
    afterEach(() => {
        filterEventRecordsStub.reset();
    });
    test('should return the new Ticker Reservation', () => {
        const fakeContext = {};
        const result = reserveTicker_1.createTickerReservationResolver(fakeContext)({});
        expect(result.ticker).toBe(tickerString);
    });
});
describe('getAuthorization', () => {
    test('should return the appropriate roles and permissions', () => {
        const ticker = 'someTicker';
        const args = {
            ticker,
            extendPeriod: true,
        };
        const permissions = {
            transactions: [types_1.TxTags.asset.RegisterTicker],
            assets: [],
            portfolios: [],
        };
        expect(reserveTicker_1.getAuthorization(args)).toEqual({
            roles: [{ type: types_2.RoleType.TickerOwner, ticker }],
            permissions,
        });
        args.extendPeriod = false;
        expect(reserveTicker_1.getAuthorization(args)).toEqual({
            permissions,
        });
    });
});
//# sourceMappingURL=reserveTicker.js.map