import { Component, OnInit, ViewChild } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IInstanceModel } from '@fleio-api/openstack/model/instance.model';
import { Observable, of } from 'rxjs';
import { IInstanceRescueOptionsModel } from '@fleio-api/openstack/model/instance-rescue-options.model';
import { ActivatedRoute, Router } from '@angular/router';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ConfigService } from '@shared/config/config.service';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';

@Component({
  selector: 'app-instance-rescue-form',
  templateUrl: './instance-rescue-form.component.html',
  styleUrls: ['./instance-rescue-form.component.scss']
})
export class InstanceRescueFormComponent extends DetailsFormBase<IInstanceModel> implements OnInit {
  @ViewChild('imagesAsCards') imagesAsCards;
  imageTypes = [
    {
      value: 'pub',
      display: $localize`Standard images`,
    },
    {
      value: 'own',
      display: $localize`Client images`,
    },
    {
      value: 'shr',
      display: $localize`Shared images`,
    }
  ]; // rescue options image options format
  imageType = this.imageTypes[0];
  rescueOptions: IInstanceRescueOptionsModel;
  rescueForm = this.formBuilder.group({
    image: ['', Validators.required],
    root_password: ['', Validators.required],
  });
  backendErrors = {};
  showPassword = false;
  bootFromIso = false;
  hasImages = false;
  holdButtonText = $localize`Hold button to reveal password`;

  imageControl = this.rescueForm.controls.image;

  constructor(
    private activatedRoute: ActivatedRoute,
    private instancesApi: InstancesApiService,
    private notificationService: NotificationService,
    private router: Router,
    private config: ConfigService,
    private formBuilder: UntypedFormBuilder,
  ) {
    super();
  }

  private rescueInstance(): Observable<IActionResult> {
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return of(null);
    }

    let request;
    if (this.bootFromIso === true) {
      request = this.instancesApi.bootFromISO(this.object.id, this.rescueForm.value);
    } else {
      request = this.instancesApi.rescue(this.object.id, this.rescueForm.value);
    }
    this.objectController.loading = true;
    request.subscribe(() => {
      if (!this.bootFromIso) {
        this.notificationService.showMessage($localize`Instance rescue scheduled`);
      } else {
        this.notificationService.showMessage($localize`Instance boot from ISO scheduled`);
      }
      this.router.navigateByUrl(
        this.config.getPanelUrl(`openstack/instances/${this.object.id}`)
      ).catch(() => {
      });
    }, error => {
      this.objectController.loading = false;
      this.backendErrors = error.error;
      this.formErrors.setBackendErrors(this.backendErrors);
      this.setErrors(this.backendErrors);
    });
    return of(null);
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.router.url.endsWith('boot-from-iso')) {
      this.bootFromIso = true;
    }
    if (this.bootFromIso) {
      this.rescueForm.removeControl('root_password');
    }
    this.rescueOptions = this.activatedRoute.snapshot.data.bootOptions;
    this.hasImages = this.rescueOptions && (
      this.rescueOptions.image.own.length +
      this.rescueOptions.image.pub.length +
      this.rescueOptions.image.shr.length) > 0;
    if (this.objectController) {
      this.objectController.actionCallback = () => this.rescueInstance();
    }
  }
}
