"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 ChartJsSqlDataProvider_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChartJsSqlDataProvider = exports.SqlExpressionOperator = void 0;
const common_1 = require("@nestjs/common");
const dashboard_question_data_provider_decorator_1 = require("../../decorators/dashboard-question-data-provider.decorator");
const typeorm_1 = require("typeorm");
const sql_expression_resolver_service_1 = require("../sql-expression-resolver.service");
const helpers_1 = require("./helpers");
var SqlExpressionOperator;
(function (SqlExpressionOperator) {
    SqlExpressionOperator["EQUALS"] = "$equals";
    SqlExpressionOperator["NOT_EQUALS"] = "$notEquals";
    SqlExpressionOperator["CONTAINS"] = "$contains";
    SqlExpressionOperator["NOT_CONTAINS"] = "$notContains";
    SqlExpressionOperator["STARTS_WITH"] = "$startsWith";
    SqlExpressionOperator["ENDS_WITH"] = "$endsWith";
    SqlExpressionOperator["IN"] = "$in";
    SqlExpressionOperator["NOT_IN"] = "$notIn";
    SqlExpressionOperator["BETWEEN"] = "$between";
    SqlExpressionOperator["LT"] = "$lt";
    SqlExpressionOperator["LTE"] = "$lte";
    SqlExpressionOperator["GT"] = "$gt";
    SqlExpressionOperator["GTE"] = "$gte";
})(SqlExpressionOperator || (exports.SqlExpressionOperator = SqlExpressionOperator = {}));
let ChartJsSqlDataProvider = ChartJsSqlDataProvider_1 = class ChartJsSqlDataProvider {
    constructor(entityManager, sqlExpressionResolver) {
        this.entityManager = entityManager;
        this.sqlExpressionResolver = sqlExpressionResolver;
        this.logger = new common_1.Logger(ChartJsSqlDataProvider_1.name);
    }
    help() {
        return "Provides data for dashboard questions using a SQL dataset configuration. Configure your SQL dataset in the admin panel, then reference it in your dashboard question to fetch data.";
    }
    name() {
        return "ChartJsSqlDataProvider";
    }
    async getData(question, context) {
        const expressions = context?.expressions || [];
        let datasetIdx = 0;
        const datasets = [];
        const labels = await (0, helpers_1.getLabels)(question, expressions, this.entityManager, this.sqlExpressionResolver);
        const kpi = await (0, helpers_1.getKpi)(question, expressions, this.entityManager, this.sqlExpressionResolver);
        for (const questionSqlDatasetConfig of question.questionSqlDatasetConfigs) {
            const sql = questionSqlDatasetConfig.sql;
            if (!sql) {
                throw new Error(`SQL dataset ${questionSqlDatasetConfig.datasetName} configuration does not contain a valid SQL query.`);
            }
            const sqlReplacementResult = this.sqlExpressionResolver.resolveSqlWithExpressions(sql, expressions || []);
            this.logger.debug(`Final Sql query for dataset [${questionSqlDatasetConfig.datasetName}] is query=[${sqlReplacementResult.rawSql}]`);
            this.logger.debug(`Final Sql query for dataset [${questionSqlDatasetConfig.datasetName}] is parameters=[${JSON.stringify(sqlReplacementResult.parameters)}]`);
            const results = await this.entityManager.query(sqlReplacementResult.rawSql, sqlReplacementResult.parameters);
            const data = [];
            for (let i = 0; i < results.length; i++) {
                const result = results[i];
                data.push(result[questionSqlDatasetConfig.valueColumnName]);
            }
            datasets.push({
                label: questionSqlDatasetConfig.datasetDisplayName,
                data: data,
                ...JSON.parse(questionSqlDatasetConfig.options || '{}'),
            });
            datasetIdx++;
        }
        return {
            kpi,
            visualizedAs: question.visualisedAs,
            visualizationData: {
                labels,
                datasets
            }
        };
    }
};
exports.ChartJsSqlDataProvider = ChartJsSqlDataProvider;
exports.ChartJsSqlDataProvider = ChartJsSqlDataProvider = ChartJsSqlDataProvider_1 = __decorate([
    (0, dashboard_question_data_provider_decorator_1.DashboardQuestionDataProvider)(),
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [typeorm_1.EntityManager, sql_expression_resolver_service_1.SqlExpressionResolverService])
], ChartJsSqlDataProvider);
//# sourceMappingURL=chartjs-sql-data-provider.service.js.map