import { inject, Injectable } from '@angular/core';
import featuresJson from '../../assets/features/features.json';
import { getConfig } from '@iqser/common-ui';
import { AppConfig } from '@red/domain';
import { NGXLogger } from 'ngx-logger';

function transform(version: string): number {
    const [major, minor, patch, release] = version.split(/[.-]/).map(x => parseInt(x, 10));
    return major * 1e7 + minor * 1e5 + patch * 1e3 + (release || 0);
}

@Injectable({
    providedIn: 'root',
})
export class FeaturesService {
    readonly #features = new Map<string, boolean>();
    readonly #config = getConfig<AppConfig>();
    readonly #logger = inject(NGXLogger);

    isEnabled(feature: string): boolean {
        // If feature is not defined in config object return true
        return this.#features.get(feature) !== false;
    }

    loadConfig() {
        const BACKEND_APP_VERSION = transform(this.#config.BACKEND_APP_VERSION as string);
        featuresJson.features.forEach(feature => {
            this.#features.set(feature.name, transform(feature.minVersion) <= BACKEND_APP_VERSION);
        });
        this.#logger.info('[INFO] Features loaded: ', this.#features);
    }
}
