"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); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DashboardQuestionService = exports.INBUILT_SQL_DATA_PROVIDERS = exports.PRIME_REACT_DATATABLE_SQL_DATA_PROVIDER_NAME = exports.PRIME_REACT_METER_GROUP_SQL_DATA_PROVIDER_NAME = exports.CHARTJS_SQL_DATA_PROVIDER_NAME = void 0;
const common_1 = require("@nestjs/common");
const core_1 = require("@nestjs/core");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const crud_service_1 = require("./crud.service");
const solid_registry_1 = require("../helpers/solid-registry");
const dashboard_question_entity_1 = require("../entities/dashboard-question.entity");
const dashboard_question_repository_1 = require("../repository/dashboard-question.repository");
var SOURCE_TYPE;
(function (SOURCE_TYPE) {
    SOURCE_TYPE["SQL"] = "sql";
    SOURCE_TYPE["PROVIDER"] = "provider";
})(SOURCE_TYPE || (SOURCE_TYPE = {}));
exports.CHARTJS_SQL_DATA_PROVIDER_NAME = 'ChartJsSqlDataProvider';
exports.PRIME_REACT_METER_GROUP_SQL_DATA_PROVIDER_NAME = 'PrimeReactMeterGroupSqlDataProvider';
exports.PRIME_REACT_DATATABLE_SQL_DATA_PROVIDER_NAME = 'PrimeReactDatatableSqlDataProvider';
exports.INBUILT_SQL_DATA_PROVIDERS = [exports.CHARTJS_SQL_DATA_PROVIDER_NAME, exports.PRIME_REACT_METER_GROUP_SQL_DATA_PROVIDER_NAME, exports.PRIME_REACT_DATATABLE_SQL_DATA_PROVIDER_NAME];
let DashboardQuestionService = class DashboardQuestionService extends crud_service_1.CRUDService {
    constructor(entityManager, repo, moduleRef, solidRegistry) {
        super(entityManager, repo, 'dashboardQuestion', 'solid-core', moduleRef);
        this.entityManager = entityManager;
        this.repo = repo;
        this.moduleRef = moduleRef;
        this.solidRegistry = solidRegistry;
        this.logger = new common_1.Logger(this.constructor.name);
    }
    async getData(id, inputExpressions = [], isPreview = false) {
        const question = await this.loadQuestion(id);
        if (!question) {
            throw new common_1.BadRequestException(`Question with id ${id} not found`);
        }
        const dashboardVariables = question.dashboard?.dashboardVariables || [];
        const expressions = this.getExpressions(isPreview, dashboardVariables, inputExpressions);
        let dataProvider = null;
        let context = {};
        if (question.sourceType === SOURCE_TYPE.SQL && ['bar', 'pie', 'line', 'donut'].includes(question.visualisedAs)) {
            dataProvider = this.solidRegistry.getDashboardQuestionDataProviderInstance(exports.CHARTJS_SQL_DATA_PROVIDER_NAME);
            context = {
                expressions,
            };
        }
        if (question.sourceType === SOURCE_TYPE.SQL && ['prime-meter-group'].includes(question.visualisedAs)) {
            dataProvider = this.solidRegistry.getDashboardQuestionDataProviderInstance(exports.PRIME_REACT_METER_GROUP_SQL_DATA_PROVIDER_NAME);
            context = {
                expressions,
            };
        }
        if (question.sourceType === SOURCE_TYPE.SQL && ['prime-datatable'].includes(question.visualisedAs)) {
            dataProvider = this.solidRegistry.getDashboardQuestionDataProviderInstance(exports.PRIME_REACT_DATATABLE_SQL_DATA_PROVIDER_NAME);
            context = {
                expressions,
            };
        }
        if (question.sourceType === SOURCE_TYPE.PROVIDER) {
            dataProvider = this.solidRegistry.getDashboardQuestionDataProviderInstance(question.providerName);
        }
        if (!dataProvider) {
            throw new common_1.NotImplementedException(`Invalid data source type ${question.sourceType}`);
        }
        return await dataProvider.getData(question, context);
    }
    getExpressions(isPreview, dashboardVariables, inputExpressions) {
        const expressions = [];
        if (isPreview) {
            const expr = dashboardVariables.map(variable => {
                return {
                    variableName: variable.variableName,
                    operator: variable.defaultOperator,
                    value: JSON.parse(variable.defaultValue || '[]'),
                };
            });
            expressions.push(...expr);
        }
        else {
            for (const variable of dashboardVariables) {
                const matchingInputExpression = inputExpressions.find(expr => expr.variableName === variable.variableName);
                if (matchingInputExpression) {
                    expressions.push(matchingInputExpression);
                }
                else {
                    expressions.push({
                        variableName: variable.variableName,
                        operator: variable.defaultOperator,
                        value: JSON.parse(variable.defaultValue || '[]'),
                    });
                }
            }
            expressions.push(...expressions);
        }
        const deduplicatedExpressions = [];
        const variableNames = new Set();
        for (const expr of expressions) {
            if (!variableNames.has(expr.variableName)) {
                deduplicatedExpressions.push(expr);
                variableNames.add(expr.variableName);
            }
        }
        return deduplicatedExpressions;
    }
    async loadQuestion(id) {
        const repo = this.entityManager.getRepository(dashboard_question_entity_1.DashboardQuestion);
        const question = await repo.findOne({
            where: {
                id,
            },
            relations: ['questionSqlDatasetConfigs', 'dashboard', 'dashboard.dashboardVariables'],
        });
        return question;
    }
};
exports.DashboardQuestionService = DashboardQuestionService;
exports.DashboardQuestionService = DashboardQuestionService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectEntityManager)()),
    __metadata("design:paramtypes", [typeorm_2.EntityManager,
        dashboard_question_repository_1.DashboardQuestionRepository,
        core_1.ModuleRef,
        solid_registry_1.SolidRegistry])
], DashboardQuestionService);
//# sourceMappingURL=dashboard-question.service.js.map