"use strict";
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 __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.VendorFinancePoolContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const display_item_present_1 = require("../../../app-toolkit/helpers/presentation/display-item.present");
const image_present_1 = require("../../../app-toolkit/helpers/presentation/image.present");
const the_graph_helper_1 = require("../../../app-toolkit/helpers/the-graph.helper");
const position_interface_1 = require("../../../position/position.interface");
const position_utils_1 = require("../../../position/position.utils");
const contract_position_template_position_fetcher_1 = require("../../../position/template/contract-position.template.position-fetcher");
const contracts_1 = require("../contracts");
const getBorrowerInfosQuery_1 = require("./getBorrowerInfosQuery");
const getLendingPoolsQuery_1 = require("./getLendingPoolsQuery");
let VendorFinancePoolContractPositionFetcher = class VendorFinancePoolContractPositionFetcher extends contract_position_template_position_fetcher_1.ContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
    }
    getContract(address) {
        return this.contractFactory.vendorFinancePool({ address, network: this.network });
    }
    getDefinitions() {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const data = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: this.subgraphUrl,
                query: getLendingPoolsQuery_1.LENDING_POOLS_QUERY,
            });
            return ((_a = data === null || data === void 0 ? void 0 : data.pools) !== null && _a !== void 0 ? _a : []).map(poolData => ({
                address: poolData.id,
                deployer: poolData._deployer,
                mintRatio: poolData._mintRatio,
                colToken: poolData._colToken,
                lendToken: poolData._lendToken,
                expiry: poolData._expiry,
                feeRate: poolData._feeRate,
                lendBalance: poolData._lendBalance,
                totalBorrowed: poolData._totalBorrowed,
            }));
        });
    }
    getTokenDefinitions({ definition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                { metaType: position_interface_1.MetaType.SUPPLIED, address: definition.colToken, network: this.network },
                { metaType: position_interface_1.MetaType.BORROWED, address: definition.lendToken, network: this.network },
                { metaType: position_interface_1.MetaType.SUPPLIED, address: definition.lendToken, network: this.network },
            ];
        });
    }
    getLabel({ contractPosition, definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const poolLabel = `${(0, image_present_1.getLabelFromToken)(contractPosition.tokens[0])}/${(0, image_present_1.getLabelFromToken)(contractPosition.tokens[1])}`;
            const dateString = new Date(parseInt(definition.expiry) * 1000).toLocaleDateString('en-US', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
            });
            return `${poolLabel} Lending Pool - ${dateString}`;
        });
    }
    getStatsItems({ contractPosition, definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const debtToken = contractPosition.tokens.find(position_utils_1.isBorrowed);
            return [
                {
                    label: 'Lending APR',
                    value: (0, display_item_present_1.buildPercentageDisplayItem)(parseInt(definition.feeRate) / 10000),
                },
                {
                    label: 'Repayment date',
                    value: new Date(parseInt(definition.expiry) * 1000).toDateString(),
                },
                {
                    label: 'Available',
                    value: (0, display_item_present_1.buildDollarDisplayItem)((parseInt(definition.lendBalance) / Math.pow(10, debtToken.decimals)) * debtToken.price),
                },
                {
                    label: 'Borrowed',
                    value: (0, display_item_present_1.buildDollarDisplayItem)((parseInt(definition.totalBorrowed) / Math.pow(10, debtToken.decimals)) * debtToken.price),
                },
                {
                    label: 'Lend ratio',
                    value: parseInt(definition.mintRatio) / Math.pow(10, 18),
                },
            ];
        });
    }
    getDataProps(_params) {
        return __awaiter(this, void 0, void 0, function* () {
            return {
                deployer: _params.definition.deployer,
                totalDeposited: parseInt(_params.definition.lendBalance) + parseInt(_params.definition.totalBorrowed),
            };
        });
    }
    getTokenBalancesPerPosition({ address, contractPosition, }) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const collateralToken = contractPosition.tokens[0];
            const lentToken = contractPosition.tokens[1];
            if (address === contractPosition.dataProps.deployer.toLowerCase()) {
                return ['0', '0', contractPosition.dataProps.totalDeposited.toString()];
            }
            const data = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: this.subgraphUrl,
                query: (0, getBorrowerInfosQuery_1.borrowerInfosQuery)(address),
            });
            const borrowerPosition = (_a = data.borrower) === null || _a === void 0 ? void 0 : _a.positions.find(({ pool }) => pool.id === contractPosition.address);
            if (!borrowerPosition)
                return [];
            const poolRate = parseInt(borrowerPosition.pool._mintRatio) / Math.pow(10, 18);
            const suppliedBalance = parseInt(borrowerPosition.totalBorrowed) / Math.pow(10, lentToken.decimals) / poolRate;
            const suppliedBalanceRaw = suppliedBalance * Math.pow(10, collateralToken.decimals);
            const borrowedBalance = parseInt(borrowerPosition.totalBorrowed);
            return [suppliedBalanceRaw.toString(), borrowedBalance.toString(), '0'];
        });
    }
};
VendorFinancePoolContractPositionFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.VendorFinanceContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.VendorFinanceContractFactory])
], VendorFinancePoolContractPositionFetcher);
exports.VendorFinancePoolContractPositionFetcher = VendorFinancePoolContractPositionFetcher;
//# sourceMappingURL=vendor-finance.pool.contract-position-fetcher.js.map