import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { ConfigService } from '@shared/config/config.service';
import { ProjectsApiService } from '@fleio-api/openstack/project/projects-api.service';
import { RbacPoliciesApiService } from '@fleio-api/openstack/rbac-policy/rbac-policies-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { Router } from '@angular/router';
import { map } from 'rxjs/operators';
import { IRBACPolicyModel } from '@fleio-api/openstack/model/rbac-policy.model';

@Component({
  selector: 'app-rbac-policy-edit-form',
  templateUrl: './rbac-policy-edit-form.component.html',
  styleUrl: './rbac-policy-edit-form.component.scss'
})
export class RbacPolicyEditFormComponent extends DetailsFormBase<IRBACPolicyModel> implements OnInit {
  rbacForm = this.formBuilder.group({
    target_project: ['', Validators.required],
  });
  projectUnselectedPlaceholder = $localize`Select target project ...`;
  projectSelectedPlaceholder = $localize`Target project`;

  projectOptionsSwitchMap: (search: string) => Observable<any>;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private config: ConfigService,
    private projectsApiService: ProjectsApiService,
    private rbacPoliciesApiService: RbacPoliciesApiService,
    private notificationService: NotificationService,
    private router: Router,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveRBACPolicy();
    }

    this.rbacForm.patchValue(this.object);

    this.projectOptionsSwitchMap = (search) => {
      return this.projectsApiService.list({search}).pipe(
        map(data => {
            let response = data.objects as any;
            response.unshift('*');
            return response;
          }
        ));
    };
  }

  saveRBACPolicy() {
    this.validate();
    if (this.rbacForm.invalid) {
      this.displayControlErrors();
      return of(null);
    }
    const value = JSON.parse(JSON.stringify(this.rbacForm.value));
    if (value.target_project?.project_id) {
      value.target_project = value.target_project.project_id;
    }

    this.objectController.loading = true;
    this.rbacPoliciesApiService.update(this.object.id, value).subscribe({
      next: () => {
        this.objectController.loading = false;
        this.router.navigateByUrl(this.config.getPanelUrl(`openstack/rbac-policies/${this.object.id}`));
        this.notificationService.showMessage($localize`RBAC policy saved`);
      },
      error: error => {
        this.objectController.loading = false;
        if (error.error) {
          this.setErrors(error.error);
        }
      }
    });
    return of(null);
  }

}
