import { AfterViewInit, Component, inject, ViewChild } from '@angular/core';
import { UserService } from '@users/user.service';
import { GeneralConfigFormComponent } from './general-config-form/general-config-form.component';
import { SmtpFormComponent } from './smtp-form/smtp-form.component';
import { BaseFormComponent, IqserListingModule } from '@iqser/common-ui';
import { SystemPreferencesFormComponent } from './system-preferences-form/system-preferences-form.component';
import { RouterHistoryService } from '@services/router-history.service';
import { TranslateModule } from '@ngx-translate/core';
import { LicenseService } from '@services/license.service';
import { ILicenseFeature } from '@red/domain';

@Component({
    selector: 'redaction-general-config-screen',
    templateUrl: './general-config-screen.component.html',
    styleUrls: ['./general-config-screen.component.scss'],
    standalone: true,
    imports: [IqserListingModule, GeneralConfigFormComponent, SystemPreferencesFormComponent, SmtpFormComponent, TranslateModule],
})
export class GeneralConfigScreenComponent extends BaseFormComponent implements AfterViewInit {
    readonly currentUser = inject(UserService).currentUser;
    readonly routerHistoryService = inject(RouterHistoryService);
    readonly licenseService = inject(LicenseService);

    @ViewChild(GeneralConfigFormComponent) generalConfigFormComponent: GeneralConfigFormComponent;
    @ViewChild(SystemPreferencesFormComponent) systemPreferencesFormComponent: SystemPreferencesFormComponent;
    @ViewChild(SmtpFormComponent) smtpFormComponent: SmtpFormComponent;
    children: BaseFormComponent[];
    smtpLicenseFeatureEnabled: boolean;

    get changed(): boolean {
        for (const child of this.children) {
            if (child?.changed) {
                return true;
            }
        }
        return false;
    }

    get valid() {
        for (const child of this.children) {
            if (!child.valid) {
                return false;
            }
        }
        return true;
    }

    ngAfterViewInit() {
        this.children = [this.generalConfigFormComponent, this.systemPreferencesFormComponent, this.smtpFormComponent];
        let licenseFeature: ILicenseFeature = this.licenseService.getFeature('configurableSMTPServer');
        this.smtpLicenseFeatureEnabled = licenseFeature != null && licenseFeature.value === true;
    }

    async save(): Promise<void> {
        for (const child of this.children) {
            if (child.changed) {
                await child.save();
            }
        }
    }
}
