import { Component, OnInit } from '@angular/core';
import { BaseFormComponent, IqserPermissionsService, LoadingService } from '@iqser/common-ui';
import { GeneralSettingsService } from '@services/general-settings.service';
import { IGeneralConfiguration } from '@red/domain';
import { ConfigService } from '@services/config.service';
import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms';
import { firstValueFrom } from 'rxjs';
import { Roles } from '@users/roles';

@Component({
    selector: 'redaction-general-config-form',
    templateUrl: './general-config-form.component.html',
})
export class GeneralConfigFormComponent extends BaseFormComponent implements OnInit {
    private _initialConfiguration: IGeneralConfiguration;

    constructor(
        private readonly _loadingService: LoadingService,
        private readonly _generalSettingsService: GeneralSettingsService,
        private readonly _configService: ConfigService,
        private readonly _formBuilder: UntypedFormBuilder,
        private readonly _permissionsService: IqserPermissionsService,
    ) {
        super();
        this.form = this._getForm();
        if (!_permissionsService.has(Roles.generalConfiguration.write)) {
            this.form.disable();
        }
    }

    async ngOnInit(): Promise<void> {
        await this._loadData();
    }

    async save() {
        this._loadingService.start();

        const configFormValues = this.form.getRawValue();

        await firstValueFrom(this._generalSettingsService.updateGeneralConfigurations(configFormValues));
        this._initialConfiguration = await firstValueFrom(this._generalSettingsService.getGeneralConfigurations());
        this._configService.updateDisplayName(this._initialConfiguration.displayName);
        this._loadingService.stop();
        await this._loadData();
    }

    private _getForm(): UntypedFormGroup {
        return this._formBuilder.group({
            forgotPasswordFunctionEnabled: [false],
            auxiliaryName: [undefined],
        });
    }

    private async _loadData() {
        this._loadingService.start();
        try {
            this._initialConfiguration = await firstValueFrom(this._generalSettingsService.getGeneralConfigurations());
            this.form.patchValue(this._initialConfiguration, { emitEvent: false });
            this.initialFormValue = this.form.getRawValue();
        } catch (e) {}

        this._loadingService.stop();
    }
}
