import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { SettingsOpenstackApiService } from '@fleio-api/core/settings-openstack-api.service';
import { IOpenstackCredentialsModel } from '@fleio-api/core/model/openstack-credentials.model';
import { IResponseWithDetailModel } from '@fleio-api/base-model/response-with-detail.model';
import { IErrorResponseModel } from '@fleio-api/base-model/error-response.model';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';

@Component({
  selector: 'app-test-credentials-dialog',
  templateUrl: './test-credentials-dialog.component.html',
  styleUrls: ['./test-credentials-dialog.component.scss']
})
export class TestCredentialsDialogComponent implements IBaseDialog, OnInit {
  testResults: IResponseWithDetailModel;
  testError: IErrorResponseModel;
  connectedTxt = $localize`Successfully connected`;
  editTxt = $localize`Edit settings`;
  saveTxt = $localize`Save settings & sync`;
  dialogTitle = $localize`Test connection results`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: this.saveTxt,
      primary: true,
      callback: () => this.saveAndSync(),
    }),
  ];
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<TestCredentialsDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { credentials: IOpenstackCredentialsModel },
    private settingsOpenstackApi: SettingsOpenstackApiService,
  ) {
  }

  ngOnInit(): void {
    this.loading = true;
    this.settingsOpenstackApi.testCredentials(this.data.credentials).subscribe(
      testResults => {
        this.testResults = testResults;
        this.dialogActions = [
          new DialogCallbackAction({
            name: this.saveTxt,
            primary: true,
            callback: () => this.saveAndSync(),
          }),
        ];
      },
      error => {
        this.testError = error.error as IErrorResponseModel;
        this.dialogActions = [
          new DialogCallbackAction({
            name: this.editTxt,
            primary: true,
            callback: () => this.saveAndSync(),
          }),
        ];
      },
    ).add(() => {
      this.loading = false;
    });
  }

  saveAndSync() {
    if (this.testError) {
      this.dialogRef.close();
    } else {
      this.dialogRef.close('save');
    }
  }
}
