"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 __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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FundamentalAndReferenceProviderUdf = void 0;
const url_join_1 = __importDefault(require("url-join"));
const content_1 = require("../../constants/content");
const delivery_1 = require("../../delivery");
const util_1 = require("../../util");
const abstract_content_provider_1 = require("../abstract-content-provider");
const data_accessor_1 = require("../data-accessor/data-accessor");
const FundamentalAndReference = __importStar(require("./interfaces"));
const fundamental_reference_util_1 = require("./fundamental-reference-util");
const config_1 = require("../../config");
class FundamentalAndReferenceProviderUdf extends abstract_content_provider_1.AbstractContentProvider {
    constructor(session, tableBuilder) {
        super(session);
        this.tableBuilder = tableBuilder;
        this.apiGroup = 'data';
        this.endpointName = 'datagrid';
        this.dataAccessor = new data_accessor_1.DataAccessorImpl(session);
        this.setConfig();
    }
    setConfig() {
        config_1.config.set('apis.data.datagrid.url', content_1.DATAGRID_UDF_URL);
        config_1.config.set('apis.data.datagrid.endpoints', { standard: content_1.DATAGRID_UDF_ENDPOINT });
    }
    async getFundamentalAndReference(params) {
        const { universe, fields } = params;
        (0, util_1.validateRequired)({ universe, fields }, ['universe', 'fields'], 'FundamentalAndReference.Params');
        const requestParams = this.prepareRequest(params);
        const response = await this.getData(requestParams);
        const buildTable = () => this.tableBuilder.build(this.prepareResponse(response));
        return this.toContentResponse(response, buildTable);
    }
    get mainEndpoint() {
        const endpointConfig = this.getEndpointConfig();
        if (!endpointConfig) {
            throw new Error(`Configuration for the endpoint '${this.endpointName}' is missed.`);
        }
        return (0, url_join_1.default)(endpointConfig.url, '/');
    }
    // preparing requests for UDF (it prepares normal request with data)
    prepareRequest(requestParams) {
        var _a;
        const { universe, fields, parameters, rowHeaders } = requestParams;
        const formattedInstruments = fundamental_reference_util_1.FundamentalReferenceUtil.formatItems(universe);
        const formattedFields = fundamental_reference_util_1.FundamentalReferenceUtil.formatUdfFields(fundamental_reference_util_1.FundamentalReferenceUtil.filterRealTimeFields(fields));
        const datagrid = config_1.config.get('apis.data.datagrid');
        const layout = (_a = datagrid === null || datagrid === void 0 ? void 0 : datagrid.layout) === null || _a === void 0 ? void 0 : _a["udf" /* UDF */];
        return this.getRequestBody(Object.assign(Object.assign(Object.assign({ instruments: formattedInstruments, fields: formattedFields }, (parameters && { parameters })), requestParams.extendedParams), (rowHeaders === FundamentalAndReference.RowHeaders.Date && layout)));
    }
    // preparing waiting-ticket-tracking requests for UDF (it prepares requests with tracking ticket)
    prepareTrackRequest(ticket) {
        return this.getRequestBody({
            ticket,
        });
    }
    // getting UDF request body (returns udf request body for requests both with data and tracking ticket)
    getRequestBody(request) {
        return {
            url: this.mainEndpoint,
            method: delivery_1.EndpointRequest.Method.POST,
            dataAccessorContentBody: {
                Entity: {
                    E: content_1.DATAGRID_UDF_DATAPOINT_NAME,
                    W: {
                        requests: [request],
                    },
                },
            },
        };
    }
    // getting data from udf (making request to udf and if udf sends back a response with a waiting ticket and
    // estimated duration, we make another request with ticket body to udf after some delay and the process
    // repeats up to maxAllowedRequestsCount times until gets a response with data. The amount of the delay
    // is determined as fallows: if estimated duration is greater than 15 sec then we take 15 sec; if it is
    // less than 15 sec we take estimated duration)
    async getData(requestParams, maxAllowedRequestsCount = content_1.UDF_MAX_REQUEST_COUNT) {
        let currentRequestParams = requestParams;
        for (let i = 0; i <= maxAllowedRequestsCount; i++) {
            const response = await this.dataAccessor.getData(currentRequestParams);
            const responseBody = this.getResponseBody(response);
            if (!('ticket' in responseBody)) {
                return response;
            }
            currentRequestParams = this.prepareTrackRequest(responseBody.ticket);
            await new Promise(resolve => setTimeout(resolve, fundamental_reference_util_1.FundamentalReferenceUtil.getWaitDuration(responseBody.estimatedDuration)));
        }
        throw new Error('The request to UDF took too long');
    }
    // preparing response structure for tableBuilder
    prepareResponse(response) {
        const responseBody = this.getResponseBody(response);
        return {
            data: responseBody.data,
            headers: fundamental_reference_util_1.FundamentalReferenceUtil.formatResponseHeaders(responseBody.headers),
        };
    }
    // getting and validating udf response body
    getResponseBody(response) {
        fundamental_reference_util_1.FundamentalReferenceUtil.validateUdfErrors(response.data);
        return response.data.responses[0];
    }
}
exports.FundamentalAndReferenceProviderUdf = FundamentalAndReferenceProviderUdf;
//# sourceMappingURL=data:application/json;base64, 