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 } from '@iqser/common-ui';
import { SystemPreferencesFormComponent } from './system-preferences-form/system-preferences-form.component';
import { RouterHistoryService } from '../../../../services/router-history.service';

@Component({
    selector: 'redaction-general-config-screen',
    templateUrl: './general-config-screen.component.html',
    styleUrls: ['./general-config-screen.component.scss'],
})
export class GeneralConfigScreenComponent extends BaseFormComponent implements AfterViewInit {
    readonly currentUser = inject(UserService).currentUser;
    readonly routerHistoryService = inject(RouterHistoryService);

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

    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];
    }

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