"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 modifyStoTimes_1 = require("../modifyStoTimes");
const mocks_1 = require("../../../testUtils/mocks");
const types_1 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/Sto', require("../../../testUtils/mocks/entities").mockStoModule('~/api/entities/Sto'));
jest.mock('~/api/entities/SecurityToken', require("../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
describe('modifyStoTimes procedure', () => {
    const ticker = 'SOMETICKER';
    const id = new bignumber_js_1.default(1);
    const now = new Date();
    const newStart = new Date(now.getTime() + 700000);
    const newEnd = new Date(newStart.getTime() + 700000);
    const start = new Date(now.getTime() + 500000);
    const end = new Date(start.getTime() + 500000);
    const rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
    const rawId = mocks_1.dsMockUtils.createMockU64(id.toNumber());
    const rawNewStart = mocks_1.dsMockUtils.createMockMoment(newStart.getTime());
    const rawNewEnd = mocks_1.dsMockUtils.createMockMoment(newEnd.getTime());
    const rawStart = mocks_1.dsMockUtils.createMockMoment(start.getTime());
    const rawEnd = mocks_1.dsMockUtils.createMockMoment(end.getTime());
    let mockContext;
    let addTransactionStub;
    let modifyFundraiserWindowTransaction;
    let dateToMomentStub;
    const args = {
        ticker,
        id,
        start: newStart,
        end: newEnd,
    };
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        sinon_1.default.stub(utilsConversionModule, 'stringToTicker').returns(rawTicker);
        sinon_1.default.stub(utilsConversionModule, 'numberToU64').returns(rawId);
        dateToMomentStub = sinon_1.default.stub(utilsConversionModule, 'dateToMoment');
    });
    beforeEach(() => {
        mocks_1.entityMockUtils.configureMocks({
            stoOptions: {
                details: {
                    status: {
                        sale: types_1.StoSaleStatus.Live,
                        timing: types_1.StoTimingStatus.NotStarted,
                        balance: types_1.StoBalanceStatus.Available,
                    },
                    start,
                    end,
                },
            },
        });
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        dateToMomentStub.withArgs(newStart, mockContext).returns(rawNewStart);
        dateToMomentStub.withArgs(newEnd, mockContext).returns(rawNewEnd);
        dateToMomentStub.withArgs(start, mockContext).returns(rawStart);
        dateToMomentStub.withArgs(end, mockContext).returns(rawEnd);
    });
    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 add a modify fundraiser window transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        modifyFundraiserWindowTransaction = mocks_1.dsMockUtils.createTxStub('sto', 'modifyFundraiserWindow');
        yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub, modifyFundraiserWindowTransaction, {}, rawTicker, rawId, rawNewStart, rawNewEnd);
        yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, Object.assign(Object.assign({}, args), { start: undefined }));
        sinon_1.default.assert.calledWith(addTransactionStub, modifyFundraiserWindowTransaction, {}, rawTicker, rawId, rawStart, rawNewEnd);
        yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, Object.assign(Object.assign({}, args), { end: null }));
        sinon_1.default.assert.calledWith(addTransactionStub, modifyFundraiserWindowTransaction, {}, rawTicker, rawId, rawNewStart, null);
        yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, Object.assign(Object.assign({}, args), { end: undefined }));
        sinon_1.default.assert.calledWith(addTransactionStub, modifyFundraiserWindowTransaction, {}, rawTicker, rawId, rawNewStart, rawEnd);
        mocks_1.entityMockUtils.configureMocks({
            stoOptions: {
                details: {
                    start,
                    end: null,
                    status: {
                        sale: types_1.StoSaleStatus.Live,
                        timing: types_1.StoTimingStatus.NotStarted,
                        balance: types_1.StoBalanceStatus.Available,
                    },
                },
            },
        });
        yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, Object.assign(Object.assign({}, args), { end: undefined }));
        sinon_1.default.assert.calledWith(addTransactionStub, modifyFundraiserWindowTransaction, {}, rawTicker, rawId, rawNewStart, null);
    }));
    test('should throw an error if nothing is being modified', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let err;
        const message = 'Nothing to modify';
        try {
            yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, Object.assign(Object.assign({}, args), { start, end }));
        }
        catch (error) {
            err = error;
        }
        expect(err === null || err === void 0 ? void 0 : err.message).toBe(message);
        err = undefined;
        try {
            yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, Object.assign(Object.assign({}, args), { start: undefined, end }));
        }
        catch (error) {
            err = error;
        }
        expect(err === null || err === void 0 ? void 0 : err.message).toBe(message);
        try {
            yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, Object.assign(Object.assign({}, args), { start, end: undefined }));
        }
        catch (error) {
            err = error;
        }
        expect(err === null || err === void 0 ? void 0 : err.message).toBe(message);
    }));
    test('should throw an error if the sto is already closed', () => {
        mocks_1.entityMockUtils.configureMocks({
            stoOptions: {
                details: {
                    status: {
                        sale: types_1.StoSaleStatus.Closed,
                        timing: types_1.StoTimingStatus.Started,
                        balance: types_1.StoBalanceStatus.Available,
                    },
                },
            },
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        return expect(modifyStoTimes_1.prepareModifyStoTimes.call(proc, args)).rejects.toThrow('The STO is already closed');
    });
    test('should throw an error if the STO has already ended', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        mocks_1.entityMockUtils.configureMocks({
            stoOptions: {
                details: {
                    start: now,
                    end: now,
                    status: {
                        sale: types_1.StoSaleStatus.Live,
                        timing: types_1.StoTimingStatus.Expired,
                        balance: types_1.StoBalanceStatus.Available,
                    },
                },
            },
        });
        let err;
        try {
            yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, args);
        }
        catch (error) {
            err = error;
        }
        expect(err === null || err === void 0 ? void 0 : err.message).toBe('The STO has already ended');
    }));
    test('should throw an error if attempting to modify the start time of an STO that has already started', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        mocks_1.entityMockUtils.configureMocks({
            stoOptions: {
                details: {
                    start: new Date(now.getTime() - 1000),
                    end,
                    status: {
                        sale: types_1.StoSaleStatus.Live,
                        timing: types_1.StoTimingStatus.Started,
                        balance: types_1.StoBalanceStatus.Available,
                    },
                },
            },
        });
        let err;
        try {
            yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, args);
        }
        catch (error) {
            err = error;
        }
        expect(err === null || err === void 0 ? void 0 : err.message).toBe('Cannot modify the start time of an STO that already started');
    }));
    test('should throw an error if the new times are in the past', () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.entityMockUtils.configureMocks({
            stoOptions: {
                details: {
                    status: {
                        timing: types_1.StoTimingStatus.NotStarted,
                        balance: types_1.StoBalanceStatus.Available,
                        sale: types_1.StoSaleStatus.Live,
                    },
                },
            },
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let err;
        const past = new Date(now.getTime() - 1000);
        const message = 'New dates are in the past';
        try {
            yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, Object.assign(Object.assign({}, args), { start: past }));
        }
        catch (error) {
            err = error;
        }
        expect(err === null || err === void 0 ? void 0 : err.message).toBe(message);
        err = undefined;
        try {
            yield modifyStoTimes_1.prepareModifyStoTimes.call(proc, Object.assign(Object.assign({}, args), { end: past }));
        }
        catch (error) {
            err = error;
        }
        expect(err === null || err === void 0 ? void 0 : err.message).toBe(message);
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = modifyStoTimes_1.getAuthorization.bind(proc);
            expect(boundFunc(args)).toEqual({
                permissions: {
                    transactions: [types_1.TxTags.sto.ModifyFundraiserWindow],
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                    portfolios: [],
                },
            });
        });
    });
});
//# sourceMappingURL=modifyStoTimes.js.map