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 { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IDbaasInstanceModel } from '@fleio-api/openstack/model/dbaas-instance.model';
import { DbaasInstancesApiService } from '@fleio-api/openstack/dbaas/dbaas-instances-api.service';

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

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

  ngOnInit() {
    this.loading = true;
    this.dbaasInstancesApiService.getDatabases(this.data.database_instance.id).subscribe(value => {
      value.databases.forEach(database => {
        if (!this.data.existing_dbs.find(dbname => dbname === database.name)) {
         this.databases.push(database.name);
        }
      });
    }).add(() => {
      this.loading = false;
    });
  }


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

}
