import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { DbaasInstancesApiService } from '@fleio-api/openstack/dbaas/dbaas-instances-api.service';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IDbaasInstanceModel } from '@fleio-api/openstack/model/dbaas-instance.model';

@Component({
  selector: 'app-create-database-user-dialog',
  templateUrl: './create-database-user-dialog.component.html',
  styleUrls: ['./create-database-user-dialog.component.scss']
})
export class CreateDatabaseUserDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  createUserForm = this.formBuilder.group({
    name: ['', [Validators.required, Validators.maxLength(16)]],
    password: ['', Validators.required],
  });
  dialogTitle = $localize`Create user`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Create user`,
      primary: true,
      callback: () => this.createUser(),
    }),
  ];
  loading = false;
  dialogForm = this.createUserForm;

  constructor(
    public dialogRef: MatDialogRef<CreateDatabaseUserDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      database_instance: IDbaasInstanceModel;
    },
    private dbaasInstancesApiService: DbaasInstancesApiService,
    private formBuilder: UntypedFormBuilder,
  ) {
  }

  ngOnInit() {
  }


  createUser() {
    if (!this.createUserForm.valid) {
      return;
    }
    const user = this.createUserForm.value;
    this.loading = true;
    this.dbaasInstancesApiService.createUser(this.data.database_instance.id, user.name, user.password).subscribe({
      next: () => {
        this.dialogRef.close(true);
      }, error: error => {
        this.formErrors.setBackendErrors(error.error);
      }
    }).add(() => {
      this.loading = false;
    });
  }

}
