import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { NotificationService } from '@shared/ui-api/notification.service';
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 { IImageModel } from '@fleio-api/openstack/model/image.model';
import { ImagesApiService } from '@fleio-api/openstack/image/image-api.service';
import { UntypedFormBuilder, Validators } from '@angular/forms';
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-api-user-download-openrc',
  templateUrl: './image-copy-dialog.html',
  styleUrls: ['./image-copy-dialog.scss']
})
export class ImageCopyDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  regions: FleioObjectsList<IRegionModel> | null;
  loading = false;
  copyForm = this.formBuilder.group({
    destination_region_id: ['', Validators.required],
    destination_name: ['', Validators.required],
    delete_source_image: [false, Validators.required],
  });
  dialogTitle = $localize`Copy image ${this.data.image.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Copy image`,
      primary: true,
      callback: () => this.copyImage(),
    }),
  ];
  dialogForm = this.copyForm;

  constructor(
    public dialogRef: MatDialogRef<ImageCopyDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { image: IImageModel },
    private imagesApi: ImagesApiService,
    private notificationService: NotificationService,
    private regionsApiService: RegionsApiService,
    private formBuilder: UntypedFormBuilder,
  ) {
  }

  public copyImage() {
    if (!this.copyForm.valid) {
      return;
    }
    const value = this.copyForm.value;
    this.loading = true;
    this.imagesApi.copyImage(
      this.data.image.id,
      value.destination_region_id,
      value.destination_name,
      value.delete_source_image,
    ).pipe().subscribe(() => {
      this.notificationService.showMessage('Image copy operation scheduled');
      this.dialogRef.close(true);
    }, error => {
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
  }

  ngOnInit() {
    this.regions = null;
    this.copyForm.controls.destination_name.patchValue(this.data.image.name);
    this.copyForm.controls.destination_region_id.patchValue(this.data.image.region);
    this.loading = true;
    this.regionsApiService.list().pipe().subscribe(response => {
      this.regions = response;
      this.loading = false;
    });
  }

}
