import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { BaseFormComponent, IconButtonTypes, IqserPermissionsService, LoadingService, Toaster } from '@iqser/common-ui';
import { ISmtpConfiguration } from '@red/domain';
import { Roles } from '@users/roles';
import { firstValueFrom } from 'rxjs';
import { AdminDialogService } from '../../../services/admin-dialog.service';
import { SmtpConfigService } from '../../../services/smtp-config.service';

@Component({
    selector: 'redaction-smtp-form',
    templateUrl: './smtp-form.component.html',
})
export class SmtpFormComponent extends BaseFormComponent implements OnInit {
    #initialConfiguration: ISmtpConfiguration;
    readonly iconButtonTypes = IconButtonTypes;

    constructor(
        private readonly _formBuilder: FormBuilder,
        private readonly _dialogService: AdminDialogService,
        private readonly _smtpConfigService: SmtpConfigService,
        private readonly _loadingService: LoadingService,
        private readonly _toaster: Toaster,
        permissionsService: IqserPermissionsService,
    ) {
        super();
        this.form = this.#getForm();
        if (!permissionsService.has(Roles.smtp.write)) {
            this.form.disable();
        }
    }

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

    onToggleAuthentication(checked: boolean): void {
        if (checked) {
            this.openAuthConfigDialog();
        }
    }

    openAuthConfigDialog(skipDisableOnCancel?: boolean) {
        this._dialogService.openDialog('smtpAuthConfig', this.form.getRawValue(), null, authConfig => {
            if (authConfig) {
                this.form.patchValue(authConfig);
            } else if (!skipDisableOnCancel) {
                this.form.patchValue({ auth: false }, { emitEvent: false });
            }
        });
    }

    async save() {
        this._loadingService.start();
        await firstValueFrom(this._smtpConfigService.updateSMTPConfiguration(this.form.getRawValue()));
        this.#initialConfiguration = this.form.getRawValue();
        this._loadingService.stop();
        await this.#loadData();
    }

    async testConnection() {
        this._loadingService.start();
        try {
            await firstValueFrom(this._smtpConfigService.testSMTPConfiguration(this.form.getRawValue()));
            this._toaster.success(_('general-config-screen.test.success'));
        } catch (e) {
            this._toaster.error(_('general-config-screen.test.error'));
        } finally {
            this._loadingService.stop();
        }
    }

    #getForm() {
        return this._formBuilder.group({
            host: [undefined, Validators.required],
            port: [25],
            from: [undefined, [Validators.required, Validators.email]],
            fromDisplayName: [undefined],
            replyTo: [undefined],
            replyToDisplayName: [undefined],
            envelopeFrom: [undefined],
            ssl: [false],
            starttls: [false],
            auth: [false],
            user: [undefined],
            password: [undefined],
        });
    }

    async #loadData() {
        this._loadingService.start();

        try {
            this.#initialConfiguration = await firstValueFrom(this._smtpConfigService.getCurrentSMTPConfiguration());
            this.form.patchValue(this.#initialConfiguration, { emitEvent: false });
        } catch (e) {}

        this.initialFormValue = this.form.getRawValue();
        this._loadingService.stop();
    }
}
