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 { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { SingleSignOnSettingsApiService } from '@fleio-api/core/single-sign-on-settings-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { catchError } from 'rxjs/operators';
import { EMPTY } from 'rxjs';

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

  constructor(
    public dialogRef: MatDialogRef<UploadNewSaml2CertificateDialogComponent>,
    @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);
  }

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

    const certificateData = this.certificateForm.value;

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