import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { catchError } from 'rxjs/operators';
import { EMPTY, Observable, of } from 'rxjs';
import { ISaml2IdentityProviderModel } from '@fleio-api/core/model/saml2-identity-provider.model';
import { Saml2IdentityProvidersApiService } from '@fleio-api/core/saml2-identity-providers-api.service';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';

@Component({
  selector: 'app-edit-saml2-identity-provider',
  templateUrl: './edit-saml2-identity-provider.component.html',
  styleUrls: ['./edit-saml2-identity-provider.component.scss']
})
export class EditSaml2IdentityProviderComponent extends DetailsFormBase<ISaml2IdentityProviderModel> implements OnInit {
  private type: string;
  forStaff: boolean;
  forEnduser: boolean;
  saml2IdentityProviderForm = this.formBuilder.group({
    name: ['', Validators.required],
    metadata: ['', Validators.required],
    metadata_url: [''],
    available_for_staff: [false],
    available_for_enduser: [false],
    image_url: [''],
    label: [''],
  });
  isNew = false;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private saml2IdentityProvidersApi: Saml2IdentityProvidersApiService,
    private router: Router,
    public config: ConfigService,
    private notificationService: NotificationService,
    private activatedRoute: ActivatedRoute
  ) {
    super();
  }

  ngOnInit() {
    if (this.object && this.object.id) {
      this.saml2IdentityProviderForm.patchValue(this.object);
    } else {
      this.isNew = true;
    }

    this.type = this.activatedRoute.snapshot.queryParams.type;
    if (this.type) {
      this.forStaff = this.type === 'staff';
      this.forEnduser = this.type === 'enduser';
      this.saml2IdentityProviderForm.patchValue({
        available_for_staff: this.forStaff,
        available_for_enduser: this.forEnduser,
      });
    }
    this.objectController.actionCallback = () => this.saveSaml2IdentityProvider();
  }

  saveSaml2IdentityProvider(): Observable<IActionResult> {
    if (this.saml2IdentityProviderForm.invalid) {
      this.displayControlErrors();
      return of(null);
    }

    const saml2IdentityProvider = this.saml2IdentityProviderForm.value as ISaml2IdentityProviderModel;
    let request;
    if (this.isNew) {
      request = this.saml2IdentityProvidersApi.create(saml2IdentityProvider);
    } else {
      request = this.saml2IdentityProvidersApi.update(this.object.id, saml2IdentityProvider);
    }

    this.objectController.loading = true;
    request.pipe(catchError((error) => {
      this.objectController.loading = false;
      if (error.error) {
        this.setErrors(error.error);
        return EMPTY;
      } else {
        throw error;
      }
    })).subscribe(() => {
      this.notificationService.showMessage(
        this.isNew ? $localize`Saml2 identity provider create` : $localize`Saml2 identity provider saved`,
      );
      this.router.navigateByUrl(
        this.config.getPanelUrl('settings/general#single-sign-on'),
      ).then(() => {
      });
    });

    return of(null);
  }

  fetchMetadata() {
    this.saml2IdentityProvidersApi.fetchMetadataFromUrl(
      this.saml2IdentityProviderForm.controls.metadata_url.value,
    ).subscribe((response) => {
      this.saml2IdentityProviderForm.controls.metadata.setValue(response.metadata);
      this.saml2IdentityProviderForm.controls.image_url.setValue(response.image_url);
    });
  }
}
