import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { EMPTY } from 'rxjs';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { NotificationService } from '@shared/ui-api/notification.service';
import { catchError } from 'rxjs/operators';
import { SingleSignOnSettingsApiService } from '@fleio-api/core/single-sign-on-settings-api.service';

@Component({
  selector: 'app-regenerate-saml2-certificate-dialog',
  templateUrl: './regenerate-saml2-certificate-dialog.component.html',
  styleUrls: ['./regenerate-saml2-certificate-dialog.component.scss']
})
export class RegenerateSaml2CertificateDialogComponent implements IBaseDialog, OnInit {
  certificateForm: UntypedFormGroup = this.formBuilder.group({
    organization_name: ['', Validators.required],
    common_name: [''],
    email_address: [''],
  });
  dialogTitle = $localize`Regenerate SAML 2 SSO certificate`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Regenerate certificate`,
      primary: true,
      callback: () => this.generateCertificate(),
    }),
  ];
  dialogForm = this.certificateForm;
  loading = false;
  @ViewChild('formErrors') formErrors;
  backendErrors: Record<string, unknown> = {};

  constructor(
    public dialogRef: MatDialogRef<RegenerateSaml2CertificateDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private formBuilder: UntypedFormBuilder,
    private ssoSettingsApi: SingleSignOnSettingsApiService,
    private notificationService: NotificationService,
  ) {
  }

  ngOnInit() {
  }

  protected displayControlErrors() {
    Object.keys(this.certificateForm.controls).map(name => {
      const control = this.certificateForm.controls[name];
      if (control.invalid) {
        control.markAsTouched();
      }
    });
  }

  protected setErrors(backendErrors: Record<string, any>) {
    this.backendErrors = backendErrors;
    this.formErrors.setBackendErrors(backendErrors);
  }

  generateCertificate() {
    if (this.certificateForm.invalid) {
      this.displayControlErrors();
      return;
    }

    const certificateData = this.certificateForm.value;

    this.loading = true;
    this.ssoSettingsApi.regenerateCertificate(certificateData).pipe(catchError((error) => {
      if (error.error) {
        this.setErrors(error.error);
        return EMPTY;
      } else {
        throw error;
      }
    })).subscribe(() => {
      this.notificationService.showMessage($localize`New SAML 2 SSO certificate generated successfully`);
      this.dialogRef.close(true);
    }).add(() => {
      this.loading = false;
    });
  }
}
