"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(require("ramda"));
const transactionFactory_1 = require("../../../../utils/solidity/transactionFactory");
const ensure_1 = require("../../../../utils/guards/ensure");
const token_math_1 = require("@melonproject/token-math");
const Contracts_1 = require("../../../../Contracts");
const getToken_1 = require("../../../dependencies/token/calls/getToken");
const balanceOf_1 = require("../../../dependencies/token/calls/balanceOf");
const getHub_1 = require("../../hub/calls/getHub");
const getRoutes_1 = require("../../hub/calls/getRoutes");
const isEmptyAddress_1 = require("../../../../utils/checks/isEmptyAddress");
const guard = (environment, { sharesQuantity }, contractAddress) => __awaiter(this, void 0, void 0, function* () {
    const hub = yield getHub_1.getHub(environment, contractAddress);
    const routes = yield getRoutes_1.getRoutes(environment, hub);
    const balance = yield balanceOf_1.balanceOf(environment, routes.sharesAddress, {
        address: environment.wallet.address,
    });
    ensure_1.ensure(token_math_1.greaterThan(balance, sharesQuantity) || token_math_1.isEqual(balance, sharesQuantity), `Address ${environment.wallet.address} doesn't have ${token_math_1.toFixed(sharesQuantity)} shares of the fund ${hub}. Only: ${token_math_1.toFixed(balance)}`);
});
const prepareArgs = (_, { sharesQuantity }) => __awaiter(this, void 0, void 0, function* () {
    return [sharesQuantity.quantity.toString()];
});
const postProcess = (environment, receipt, _, contractAddress) => __awaiter(this, void 0, void 0, function* () {
    const hub = yield getHub_1.getHub(environment, contractAddress);
    const routes = yield getRoutes_1.getRoutes(environment, hub);
    const fundToken = yield getToken_1.getToken(environment, routes.sharesAddress);
    const redemption = receipt.events.Redemption.returnValues;
    ensure_1.ensure(!!redemption, 'No Redemption log found in transaction');
    const redemptionAddressQuantityPairs = R.zip(redemption.assets, redemption.assetQuantities);
    const redemptionsPromises = redemptionAddressQuantityPairs.map(([tokenAddress, quantity]) => __awaiter(this, void 0, void 0, function* () {
        const token = isEmptyAddress_1.isEmptyAddress(tokenAddress)
            ? token_math_1.createToken('EMPTY')
            : yield getToken_1.getToken(environment, tokenAddress);
        return token_math_1.createQuantity(token, quantity);
    }));
    const redemptions = yield Promise.all(redemptionsPromises);
    const redeemedShares = token_math_1.createQuantity(fundToken, redemption.redeemedShares);
    return {
        redeemedShares,
        redemptions: redemptions.filter((q) => !token_math_1.isZero(q) && q.token.symbol !== 'EMPTY'),
    };
});
const redeemQuantity = transactionFactory_1.transactionFactory('redeemQuantity', Contracts_1.Contracts.Participation, guard, prepareArgs, postProcess);
exports.redeemQuantity = redeemQuantity;
