"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 PrimeReactMeterGroupSqlDataProvider_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PrimeReactMeterGroupSqlDataProvider = 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 common_2 = require("@nestjs/common");
const helpers_1 = require("./helpers");
let PrimeReactMeterGroupSqlDataProvider = PrimeReactMeterGroupSqlDataProvider_1 = class PrimeReactMeterGroupSqlDataProvider {
    constructor(entityManager, sqlExpressionResolver) {
        this.entityManager = entityManager;
        this.sqlExpressionResolver = sqlExpressionResolver;
        this.logger = new common_2.Logger(PrimeReactMeterGroupSqlDataProvider_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 "PrimeReactMeterGroupSqlDataProvider";
    }
    hslToHex(h, s, l) {
        l /= 100;
        s /= 100;
        const k = (n) => (n + h / 30) % 12;
        const a = s * Math.min(l, 1 - l);
        const f = (n) => Math.round(255 * (l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)))));
        return `#${f(0).toString(16).padStart(2, '0')}${f(8).toString(16).padStart(2, '0')}${f(4)
            .toString(16)
            .padStart(2, '0')}`;
    }
    generateDistinctColors(count) {
        const colors = [];
        const hueStep = 360 / count;
        const saturation = 65;
        const lightness = 55;
        for (let i = 0; i < count; i++) {
            const hue = Math.round(i * hueStep);
            colors.push(this.hslToHex(hue, saturation, lightness));
        }
        return colors;
    }
    async getData(question, context) {
        const expressions = context?.expressions || [];
        const kpi = await (0, helpers_1.getKpi)(question, expressions, this.entityManager, this.sqlExpressionResolver);
        const chartOptions = JSON.parse(question.chartOptions || '{}');
        const values = [];
        const questionSqlDatasetConfig = question.questionSqlDatasetConfigs[0];
        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 colors = this.generateDistinctColors(results.length);
        for (let i = 0; i < results.length; i++) {
            const result = results[i];
            const colorFromChartOptions = chartOptions?.colors?.[result[questionSqlDatasetConfig.labelColumnName]];
            const color = typeof colorFromChartOptions === 'string' ? colorFromChartOptions : colors[i];
            values.push({
                label: result[questionSqlDatasetConfig.labelColumnName],
                color: color,
                value: result[questionSqlDatasetConfig.valueColumnName]
            });
        }
        return {
            kpi,
            visualizedAs: question.visualisedAs,
            visualizationData: {
                dataset: values
            },
        };
    }
};
exports.PrimeReactMeterGroupSqlDataProvider = PrimeReactMeterGroupSqlDataProvider;
exports.PrimeReactMeterGroupSqlDataProvider = PrimeReactMeterGroupSqlDataProvider = PrimeReactMeterGroupSqlDataProvider_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])
], PrimeReactMeterGroupSqlDataProvider);
//# sourceMappingURL=prime-react-meter-group-sql-data-provider.service.js.map