import { Component, OnDestroy, ViewChild } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { SettingsApiService } from '@fleio-api/core/settings-api.service';
import { SfaTypesApiService } from '@fleio-api/core/sfa-types-api.service';
import { ISfaSettingsModel } from '@fleio-api/core/model/sfa-settings.model';
import { ISfaTypeModel } from '@fleio-api/core/model/sfa-type.model';
import { UntypedFormBuilder } from '@angular/forms';
import { NotificationService } from '@shared/ui-api/notification.service';
import { Observable, zip } from 'rxjs';

@Component({
  selector: 'app-authentication',
  templateUrl: './authentication.component.html',
  styleUrls: ['./authentication.component.scss']
})
export class AuthenticationComponent extends DetailsComponentBase<IBaseFleioObjectModel> implements OnDestroy {
  @ViewChild('formErrors') formErrors;
  backendErrors = null;
  sfaSettings: ISfaSettingsModel;
  sfaTypes: ISfaTypeModel[];

  sfaSettingsForm = this.formBuilder.group({
    require_staff_users_to_use_sfa: [false],
    require_end_users_to_use_sfa: [false],
  });

  disableSfaTooltip = $localize`Once disabled, users that use this
  method will not be required anymore
  to complete second factor auth step.
  They will also need to reconfigure second
  factor authentication if you'll re-enable this.`;

  constructor(
    private settingsApi: SettingsApiService, private sfaTypesApi: SfaTypesApiService, private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
  ) {
    super();
  }

  protected initTabData() {
    this.settingsApi.getSfaSettings().subscribe(sfaSettings => {
      this.sfaSettings = sfaSettings;
      this.sfaSettingsForm.patchValue(sfaSettings);
    }, error => {
      if (error.status === 403) {
        this.sfaSettingsForm.disable();
      }
    });
    this.sfaTypesApi.getForSettings().subscribe(sfaTypes => {
      this.sfaTypes = sfaTypes.objects;
    });
  }

  ngOnDestroy(): void {
  }

  saveSfaSettings(): Observable<any> {
    const sfaSettings = this.sfaSettingsForm.value;
    return this.settingsApi.saveSfaSettings(sfaSettings);
  }

  saveSfaTypes(): Observable<any> {
    const requests = [];
    for (const sfaType of this.sfaTypes) {
      requests.push(this.sfaTypesApi.update(sfaType.id, sfaType));
    }

    return zip(...requests);
  }

  saveSettings() {
    const saveSettings = zip(
      this.saveSfaSettings(),
      this.saveSfaTypes(),
    );

    this.objectController.loading = true;
    saveSettings.subscribe({
      next: () => {
        this.notificationService.showMessage($localize`Authentication settings saved`);
      },
      error: error => {
        if (error.error) {
          this.backendErrors = error.error;
          this.formErrors.setBackendErrors(error.error);
        }
      }
    }).add(() => {
      this.objectController.loading = false;
    });
  }
}
