import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ApiUsersApiService } from '@fleio-api/openstack/api-user/api-users-api.service';
import { IApiUserModel } from '@fleio-api/openstack/model/api-user.model';
import { RegionsApiService } from '@fleio-api/openstack/region/regions-api.service';
import { IRegionModel } from '@fleio-api/openstack/model/region.model';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
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-api-user-download-openrc',
  templateUrl: './api-user-download-openrc.component.html',
  styleUrls: ['./api-user-download-openrc.component.scss']
})
export class ApiUserDownloadOpenrcComponent implements IBaseDialog, OnInit {
  regionsResponse: FleioObjectsList<IRegionModel> | null;
  selectedRegion: IRegionModel;
  dialogTitle = $localize`Get OpenRC file for ${this.data?.apiUser?.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Get file`,
      primary: true,
      callback: () => this.getOpenRCFile(),
    }),
  ];
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<ApiUserDownloadOpenrcComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { apiUser: IApiUserModel },
    private apiUsersApiService: ApiUsersApiService,
    private notificationService: NotificationService,
    private regionsApiService: RegionsApiService,
  ) {
  }

  public getOpenRCFile() {
    if (!this.selectedRegion) {
      return;
    }
    this.loading = true;
    this.apiUsersApiService.getOpenRcFile(
      this.data.apiUser.name,
      this.data.apiUser.default_project_id,
      this.selectedRegion,
    ).pipe().subscribe(responseData => {
      const blob = new Blob([responseData.content], {type: 'application/octet-stream'});
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = 'openrc';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      this.dialogRef.close(true);
    }).add(() => {
      this.loading = false;
    });
  }

  ngOnInit() {
    this.regionsResponse = null;
    this.loading = true;
    this.regionsApiService.list().pipe().subscribe(response => {
      this.regionsResponse = response;
      this.loading = false;
    });
  }

}
