import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { IRegionModel } from '@fleio-api/openstack/model/region.model';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IApiUserModel } from '@fleio-api/openstack/model/api-user.model';
import { ApiUsersApiService } from '@fleio-api/openstack/api-user/api-users-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IClusterModel } from '@fleio-api/openstack/model/cluster.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ClustersApiService } from '@fleio-api/openstack/cluster/clusters-api.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';

@Component({
  selector: 'app-cluster-get-file-dialog',
  templateUrl: './cluster-get-file-dialog.component.html',
  styleUrls: ['./cluster-get-file-dialog.component.scss']
})
export class ClusterGetFileDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  regionsResponse: FleioObjectsList<IRegionModel> | null;
  selectedRegion: IRegionModel;
  getFileForm = this.formBuilder.group({
    os_user_api_username: ['', Validators.required],
    os_user_api_password: ['', Validators.required],
  });
  dialogTitle = null;
  dialogActions: Array<IAction> = [];
  dialogForm = this.getFileForm;
  loading = false;
  backendErrors = {};

  constructor(
    public dialogRef: MatDialogRef<ClusterGetFileDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      type: string;
      cluster: IClusterModel;
      apiUsers: Array<IApiUserModel>;
    },
    private apiUsersApiService: ApiUsersApiService,
    private notificationService: NotificationService,
    private clustersApiService: ClustersApiService,
    private formBuilder: UntypedFormBuilder,
  ) {
  }

  public getFile() {
    if (!this.getFileForm.valid) {
      return;
    }
    const action = `get_${this.data.type}`;
    let ending: string;
    let contentType: string;
    if (this.data.type === 'certificate') {
      ending = '_ca.pem';
      contentType = 'application/x-x509-ca-cert';
    } else if (this.data.type === 'configuration') {
      ending = '_config';
      contentType = 'application/octet-stream';
    }
    this.loading = true;
    this.clustersApiService.getFile(
      this.data.cluster.id,
      action,
      this.getFileForm.controls.os_user_api_username.value,
      this.getFileForm.controls.os_user_api_password.value
    ).subscribe(response => {
      const blob = new Blob([response.content], { type: contentType });
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = this.data.cluster.name + ending;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      this.dialogRef.close(true);
    }, error => {
      this.backendErrors = error.error;
      this.formErrors.setBackendErrors(this.backendErrors);
    }).add(() => {
      this.loading = false;
    });
  }

  ngOnInit() {
    if (this.data.type === 'configuration') {
      this.dialogTitle = $localize`Get configuration for ${this.data.cluster.name}`;
      this.dialogActions.push(
        new DialogCallbackAction({
          name: $localize`Get configuration`,
          primary: true,
          callback: () => this.getFile(),
        }),
      );
    } else {
      this.dialogTitle = $localize`Get certificate for ${this.data.cluster.name}`;
      this.dialogActions.push(
        new DialogCallbackAction({
          name: $localize`Get certificate`,
          primary: true,
          callback: () => this.getFile(),
        }),
      );
    }
  }

}
