"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 __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 __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
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.DashboardService = exports.SQL_DYNAMIC_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 fs = __importStar(require("fs/promises"));
const create_dashboard_variable_dto_1 = require("../dtos/create-dashboard-variable.dto");
const dashboard_variable_entity_1 = require("../entities/dashboard-variable.entity");
const module_metadata_helper_service_1 = require("../helpers/module-metadata-helper.service");
const solid_registry_1 = require("../helpers/solid-registry");
const dashboard_mapper_1 = require("../mappers/dashboard-mapper");
const dashboard_repository_1 = require("../repository/dashboard.repository");
exports.SQL_DYNAMIC_PROVIDER_NAME = 'DashboardVariableSQLDynamicProvider';
let DashboardService = class DashboardService extends crud_service_1.CRUDService {
    constructor(entityManager, repo, moduleRef, solidRegistry, moduleMetadataHelperService, dashboardMapper) {
        super(entityManager, repo, 'dashboard', 'solid-core', moduleRef);
        this.entityManager = entityManager;
        this.repo = repo;
        this.moduleRef = moduleRef;
        this.solidRegistry = solidRegistry;
        this.moduleMetadataHelperService = moduleMetadataHelperService;
        this.dashboardMapper = dashboardMapper;
        this.logger = new common_1.Logger(this.constructor.name);
    }
    async create(createDto, files) {
        createDto.name = createDto.name.trim().replace(/\s+/g, '-').toLowerCase();
        return super.create(createDto, files);
    }
    async getSelectionDynamicValues(query) {
        const dashboardVariable = await this.loadDashboardVariable(query.variableId);
        const [providerName, context] = this.getProviderNameAndContext(dashboardVariable, query);
        const selectionProviderInstance = this.solidRegistry.getDashboardVariableSelectionProviderInstance(providerName);
        if (!selectionProviderInstance) {
            throw new common_1.NotFoundException(`Field incorrectly configured. No provider with name ${providerName} registered in backend.`);
        }
        return selectionProviderInstance.values(query.query, context);
    }
    getProviderNameAndContext(dashboardVariable, query) {
        const sourceType = dashboardVariable.selectionDynamicSourceType;
        let providerName;
        const context = { limit: query.limit, offset: query.offset };
        switch (sourceType) {
            case create_dashboard_variable_dto_1.SelectionDynamicSourceType.SQL:
                providerName = exports.SQL_DYNAMIC_PROVIDER_NAME;
                context['sql'] = dashboardVariable.selectionDynamicSQL;
                break;
            case create_dashboard_variable_dto_1.SelectionDynamicSourceType.PROVIDER:
                providerName = dashboardVariable.selectionDynamicProviderName;
                break;
            default:
                throw new Error(`Unsupported selection dynamic source type: ${sourceType}`);
        }
        return [providerName, context];
    }
    async loadDashboardVariable(variableId) {
        const dashboardVariableRepo = this.entityManager.getRepository(dashboard_variable_entity_1.DashboardVariable);
        const dashboardVariable = await dashboardVariableRepo.findOne({
            where: {
                id: variableId,
            },
        });
        return dashboardVariable;
    }
    async saveDashboardToConfig(entity) {
        if (!entity) {
            this.logger.debug('No entity found in the DashboardSubscriber saveDashboardToConfig method');
            return;
        }
        const dashboard = entity;
        const moduleMetadata = entity.module;
        if (!moduleMetadata) {
            throw new Error(`Module metadata not found for dashboard id ${entity.id}`);
        }
        const { filePath, metaData } = await this.getConfigFileDetails(moduleMetadata.name);
        if (!filePath || !metaData) {
            throw new Error(`Configuration details not found for module: ${moduleMetadata.name}`);
        }
        await this.writeToConfig(metaData, dashboard, filePath);
    }
    async getConfigFileDetails(moduleName) {
        const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(moduleName);
        try {
            await fs.access(filePath);
        }
        catch (error) {
            throw new Error(`Configuration file not found for module: ${moduleName}`);
        }
        const metaData = await this.moduleMetadataHelperService.getModuleMetadataConfiguration(filePath);
        return { filePath, metaData };
    }
    async writeToConfig(metaData, dashboard, filePath) {
        if (metaData.dashboards && Array.isArray(metaData.dashboards)) {
            const dashboardIndex = metaData.dashboards?.findIndex((dashboardFromFile) => dashboardFromFile.name === dashboard.name);
            const dto = await this.dashboardMapper.toDto(dashboard);
            if (dashboardIndex !== -1) {
                metaData.dashboards[dashboardIndex] = dto;
            }
            else {
                metaData.dashboards.push(dto);
            }
        }
        else {
            const dashboards = [];
            const dto = await this.dashboardMapper.toDto(dashboard);
            dashboards.push(dto);
            metaData.dashboards = dashboards;
        }
        const updatedContent = JSON.stringify(metaData, null, 2);
        await fs.writeFile(filePath, updatedContent);
    }
};
exports.DashboardService = DashboardService;
exports.DashboardService = DashboardService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectEntityManager)()),
    __metadata("design:paramtypes", [typeorm_2.EntityManager,
        dashboard_repository_1.DashboardRepository,
        core_1.ModuleRef,
        solid_registry_1.SolidRegistry,
        module_metadata_helper_service_1.ModuleMetadataHelperService,
        dashboard_mapper_1.DashboardMapper])
], DashboardService);
//# sourceMappingURL=dashboard.service.js.map