import { Component } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { SystemPreferences } from '@red/domain';
import { BaseFormComponent, IqserPermissionsService, LoadingService } from '@iqser/common-ui';
import { SystemPreferencesService } from '@services/system-preferences.service';
import { systemPreferencesTranslations } from '@translations/system-preferences-translations';
import { Roles } from '@users/roles';
import { KeysOf } from '@iqser/common-ui/lib/utils';

export type ValueType = 'number' | 'string' | 'boolean';

@Component({
    selector: 'redaction-system-preferences-form',
    templateUrl: './system-preferences-form.component.html',
})
export class SystemPreferencesFormComponent extends BaseFormComponent {
    #initialConfiguration: SystemPreferences;
    readonly translations = systemPreferencesTranslations;
    readonly keys: { name: KeysOf<SystemPreferences>; type: ValueType }[] = [
        { name: 'softDeleteCleanupTime', type: 'number' },
        { name: 'downloadCleanupNotDownloadFilesHours', type: 'number' },
        { name: 'downloadCleanupDownloadFilesHours', type: 'number' },
    ];

    constructor(
        private readonly _loadingService: LoadingService,
        private readonly _systemPreferencesService: SystemPreferencesService,
        private readonly _formBuilder: UntypedFormBuilder,
        permissionsService: IqserPermissionsService,
    ) {
        super();
        this.form = this.#getForm();
        this.#loadData();
        if (!permissionsService.has(Roles.appConfiguration.write)) {
            this.form.disable();
        }
    }

    async save(): Promise<void> {
        this._loadingService.start();
        await this._systemPreferencesService.update(this.form.getRawValue());
        this.#loadData();
        this._loadingService.stop();
    }

    #getForm() {
        const controlsConfig = {};
        this.keys.forEach(key => {
            controlsConfig[key.name] = [this._systemPreferencesService.values[key.name], Validators.required];
        });
        return this._formBuilder.group(controlsConfig);
    }

    #loadData() {
        this.#initialConfiguration = this._systemPreferencesService.values;
        this.form.patchValue(this.#initialConfiguration, { emitEvent: false });
        this.initialFormValue = this.form.getRawValue();
    }
}
