"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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SymphonyYoloContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const axios_1 = __importDefault(require("axios"));
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const graphql_request_1 = require("graphql-request");
const lodash_1 = require("lodash");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const drill_balance_helper_1 = require("../../../app-toolkit/helpers/drill-balance.helper");
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 custom_contract_position_template_position_fetcher_1 = require("../../../position/template/custom-contract-position.template.position-fetcher");
const _types_1 = require("../../../types");
const contracts_1 = require("../contracts");
const USER_OPEN_ORDERS_QUERY = (0, graphql_request_1.gql) `
  query GetOrdersByOwner($creator: String) {
    orders(where: { creator: $creator, status: ACTIVE }) {
      id
      inputToken
      inputAmount
    }
  }
`;
let SymphonyYoloContractPositionFetcher = class SymphonyYoloContractPositionFetcher extends custom_contract_position_template_position_fetcher_1.CustomContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
    }
    getContract(address) {
        return this.contractFactory.symphonyYolo({ address, network: this.network });
    }
    getDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            const tokenlistUrl = 'https://raw.githubusercontent.com/symphony-finance/token-list/master/symphony.tokenlist.json';
            return (yield axios_1.default.get(tokenlistUrl)).data.tokens
                .filter(data => data.chainId == _types_1.NETWORK_IDS[this.network] && !data.extensions.isNative)
                .map(token => ({ address: this.yoloAddress, tokenAddress: token.address }));
        });
    }
    getTokenDefinitions({ definition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [{ metaType: position_interface_1.MetaType.SUPPLIED, address: definition.tokenAddress, network: this.network }];
        });
    }
    getLabel({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return `${(0, image_present_1.getLabelFromToken)(contractPosition.tokens[0])} Order`;
        });
    }
    getTokenBalancesPerPosition() {
        return __awaiter(this, void 0, void 0, function* () {
            throw new Error('Method not implemented.');
        });
    }
    getBalances(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const contractPositions = yield this.appToolkit.getAppContractPositions({
                appId: this.appId,
                groupIds: [this.groupId],
                network: this.network,
            });
            const openOrdersData = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: this.subgraphUrl,
                query: USER_OPEN_ORDERS_QUERY,
                variables: { creator: address },
            });
            const contractPositionBalances = yield Promise.all(contractPositions.map((contractPosition) => __awaiter(this, void 0, void 0, function* () {
                const orders = openOrdersData.orders.filter(p => p.inputToken.toLocaleLowerCase() === contractPosition.address.toLocaleLowerCase());
                const claimableToken = contractPosition.tokens.find(position_utils_1.isSupplied);
                const totalSupplied = orders.reduce((acc, a) => acc.plus(new bignumber_js_1.default(a.inputAmount)), new bignumber_js_1.default(0));
                const suppliedTokenBalance = (0, drill_balance_helper_1.drillBalance)(claimableToken, totalSupplied.toString());
                const tokens = [suppliedTokenBalance];
                const balanceUSD = (0, lodash_1.sumBy)(tokens, t => t.balanceUSD);
                return Object.assign(Object.assign({}, contractPosition), { tokens, balanceUSD });
            })));
            return contractPositionBalances;
        });
    }
};
SymphonyYoloContractPositionFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.SymphonyContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.SymphonyContractFactory])
], SymphonyYoloContractPositionFetcher);
exports.SymphonyYoloContractPositionFetcher = SymphonyYoloContractPositionFetcher;
//# sourceMappingURL=symphony.yolo.contract-position-fetcher.js.map