import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IApiUserModel } from '@fleio-api/openstack/model/api-user.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { ApiUsersApiService } from '@fleio-api/openstack/api-user/api-users-api.service';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-api-user-edit-form',
  templateUrl: './api-user-edit-form.component.html',
  styleUrls: ['./api-user-edit-form.component.scss']
})
export class ApiUserCreateFormComponent extends DetailsFormBase<IApiUserModel> implements OnInit {
  apiUserForm = this.formBuilder.group({
    name: ['', Validators.required],
    password: ['', Validators.required],
    description: ['', Validators.maxLength(1024)],
  });
  passwordCtrl = this.apiUserForm.controls.password;
  createInClientProject = true;

  constructor(
    private formBuilder: UntypedFormBuilder, private apiUsersApiService: ApiUsersApiService, private router: Router,
    private config: ConfigService, private notificationService: NotificationService,
  ) {
    super();
  }

  changeDestination(value) {
    // createInClientProject
    if (value === false) {
      this.apiUserForm.controls.client.setValue('');
      this.apiUserForm.controls.client.clearValidators();
      this.apiUserForm.controls.client.reset();
    } else {
      this.apiUserForm.controls.client.setValidators(Validators.required);
    }
  }

  private saveUser(): Observable<IActionResult> {
    const value = this.apiUserForm.value as any;
    if (this.authSvc.feature('ui.openstack.api-users.show-project')) {
      if (value.client && value.client.id) {
        value.client = value.client.id;
      }
    }

    if (!this.object.id && !this.createInClientProject) {
      value.create_as_admin = true;
    }

    this.createOrUpdate(this.apiUsersApiService, value).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`API user created.`);
        this.router.navigateByUrl(
          this.config.getPrevUrl('openstack/api-users')
        ).catch(() => {
        });
      }, error: () => {
        this.notificationService.showMessage($localize`Failed to create API user.`);
      }
    });
    return of(null);
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.authSvc.feature('ui.openstack.api-users.show-project')) {
      this.apiUserForm.addControl(
        'client',
        this.formBuilder.control('', Validators.required),
      );
    }
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveUser();
    }
  }
}
