import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IVolumeModel } from '@fleio-api/openstack/model/volume.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { EMPTY, Observable, of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { IImageCreateOptionsModel } from '@fleio-api/openstack/model/image-create-options.model';
import { VolumesApiService } from '@fleio-api/openstack/volume/volumes-api.service';

@Component({
  selector: 'app-volume-upload-to-image-form',
  templateUrl: './volume-upload-to-image-form.component.html',
  styleUrls: ['./volume-upload-to-image-form.component.scss']
})
export class VolumeUploadToImageFormComponent extends DetailsFormBase<IVolumeModel> implements OnInit {
  uploadToImageForm = this.formBuilder.group({
    image_name: ['', Validators.required],
    disk_format: ['raw', Validators.required],
  });

  imageCreateOptions: IImageCreateOptionsModel;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private volumesApi: VolumesApiService,
    private router: Router,
    private config: ConfigService,
    private activatedRoute: ActivatedRoute,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    this.imageCreateOptions = this.activatedRoute.snapshot.data.imageCreateOptions;

    if (this.objectController) {
      this.objectController.actionCallback = () => this.uploadVolumeToImage();
    }
  }

  uploadVolumeToImage(): Observable<IActionResult> {
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return EMPTY;
    }

    const value = this.uploadToImageForm.value;

    this.objectController.loading = true;
    this.volumesApi.uploadToImage(this.object.id, value).subscribe((response) => {
      const imageId = response.image_id;
      this.router.navigateByUrl(this.config.getPanelUrl(`openstack/images/${imageId}`)).then(() => {
      });
    }, (error) => {
      this.objectController.loading = false;
      if (error.error) {
        this.setErrors(error.error);
      }
    });

    return of(null);
  }
}
