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 ApiUserEditFormComponent extends DetailsFormBase<IApiUserModel> implements OnInit {
  apiUserForm = this.formBuilder.group({
    name: ['', Validators.required],
    password: [null],
    description: ['', Validators.maxLength(1024)],
  });
  passwordCtrl = this.apiUserForm.controls.password;

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

  private saveApiUser(): Observable<IActionResult> {
    const value = this.apiUserForm.value as any;
    if (value.password === null) {
      delete value.password;
    }
    this.createOrUpdate(this.apiUsersApiService, value).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`API user updated.`);
        this.redirectAfterCreate('openstack/api-users', this.router, this.config);
      }
    });
    return of(null);
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveApiUser();
    }
    if (this.object) {
      this.apiUserForm.patchValue(this.object);
    }
  }

}
