"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
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 __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BalancePresentationService = void 0;
const common_1 = require("@nestjs/common");
const lodash_1 = __importStar(require("lodash"));
const balance_fetcher_response_present_1 = require("../app-toolkit/helpers/presentation/balance-fetcher-response.present");
const app_service_1 = require("../app/app.service");
const position_fetcher_template_registry_1 = require("../position/position-fetcher.template-registry");
const position_presenter_registry_1 = require("../position/position-presenter.registry");
let BalancePresentationService = class BalancePresentationService {
    constructor(positionPresenterRegistry, positionFetcherTemplateRegistry, appService) {
        this.positionPresenterRegistry = positionPresenterRegistry;
        this.positionFetcherTemplateRegistry = positionFetcherTemplateRegistry;
        this.appService = appService;
    }
    groupBalancesByPositionGroup(balances, positionGroup) {
        const getDynamicLabel = (label) => {
            const matches = label.match(/{{(.*)}}/);
            if (!matches)
                return null;
            return matches[1].trim();
        };
        const dynamicLabel = getDynamicLabel(positionGroup.label);
        if (!dynamicLabel)
            return { [positionGroup.label]: balances.filter(({ groupId }) => positionGroup.groupIds.includes(groupId)) };
        else {
            return (0, lodash_1.groupBy)(balances, balance => (0, lodash_1.get)(balance, dynamicLabel));
        }
    }
    presentTemplates({ appId, network, balances, dataProps, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.presentBalances(appId, network, balances, dataProps);
        });
    }
    present({ appId, balances }) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const app = yield this.appService.getApp(appId);
            const products = Object.values((_a = app.groups) !== null && _a !== void 0 ? _a : {}).map(group => {
                const groupBalances = balances.filter(v => v.groupId === group.id);
                return { label: group.label, assets: groupBalances };
            });
            const collapsedProducts = lodash_1.default.values((0, lodash_1.groupBy)(products, v => v.label)).map(t => ({
                label: t[0].label,
                assets: t.flatMap(v => v.assets),
            }));
            return (0, balance_fetcher_response_present_1.presentBalanceFetcherResponse)(collapsedProducts);
        });
    }
    getBalanceProductGroups(appId, network) {
        const templates = this.positionFetcherTemplateRegistry.getTemplatesForAppOnNetwork(appId, network);
        const groups = templates
            .filter(template => !template.isExcludedFromBalances)
            .map(template => ({
            label: template.groupLabel,
            groupIds: [template.groupId],
        }));
        const groupedByLabel = (0, lodash_1.groupBy)(groups, group => group.label);
        return lodash_1.default.map(groupedByLabel, (groups, label) => ({
            label,
            groupIds: lodash_1.default.uniq(groups.flatMap(({ groupIds }) => groupIds)),
        }));
    }
    balanceDataProps({ appId, network, address }) {
        return __awaiter(this, void 0, void 0, function* () {
            const presenter = this.positionPresenterRegistry.get(appId, network);
            if (!presenter)
                return;
            const dataProps = yield presenter.dataProps(address);
            return dataProps;
        });
    }
    groupBalances(appId, network, balances) {
        var _a;
        const presenter = this.positionPresenterRegistry.get(appId, network);
        const positionGroups = (_a = presenter === null || presenter === void 0 ? void 0 : presenter.positionGroups) !== null && _a !== void 0 ? _a : this.getBalanceProductGroups(appId, network);
        return positionGroups
            .map(group => this.groupBalancesByPositionGroup(balances, group))
            .reduce((acc, v) => {
            Object.entries(v).forEach(([groupLabel, balances]) => {
                acc[groupLabel] = (acc[groupLabel] || []).concat(balances);
            });
            return acc;
        }, {});
    }
    presentBalances(appId, network, balances, dataProps) {
        const balancesByGroupLabel = this.groupBalances(appId, network, balances);
        const presenter = this.positionPresenterRegistry.get(appId, network);
        const products = (0, lodash_1.default)(balancesByGroupLabel)
            .mapValues((assets, label) => {
            if (!assets.length)
                return;
            const meta = presenter && presenter.metadataItemsForBalanceGroup(label, assets, dataProps);
            return Object.assign({ label,
                assets }, (meta && { meta }));
        })
            .values()
            .compact()
            .value();
        return (0, balance_fetcher_response_present_1.presentBalanceFetcherResponse)(products);
    }
};
BalancePresentationService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Inject)(position_presenter_registry_1.PositionPresenterRegistry)),
    __param(1, (0, common_1.Inject)(position_fetcher_template_registry_1.PositionFetcherTemplateRegistry)),
    __param(2, (0, common_1.Inject)(app_service_1.AppService)),
    __metadata("design:paramtypes", [position_presenter_registry_1.PositionPresenterRegistry,
        position_fetcher_template_registry_1.PositionFetcherTemplateRegistry,
        app_service_1.AppService])
], BalancePresentationService);
exports.BalancePresentationService = BalancePresentationService;
//# sourceMappingURL=balance-presentation.service.js.map