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 { ActivatedRoute, Router } from '@angular/router';
import { of } from 'rxjs';
import { IInstanceRebuildOptionsModel } from '@fleio-api/openstack/model/instance-rebuild-options.model';
import { ISelectedBootSource } from '../instance-create-form/boot-source-select/boot-source-select.component';
import { ConfigService } from '@shared/config/config.service';
import { UntypedFormBuilder } from '@angular/forms';
import { NotificationService } from '@shared/ui-api/notification.service';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';

@Component({
  selector: 'app-instance-rebuild-form',
  templateUrl: './instance-rebuild-form.component.html',
  styleUrls: ['./instance-rebuild-form.component.scss']
})
export class InstanceRebuildFormComponent extends DetailsFormBase<IInstanceModel> implements OnInit {
  @ViewChild('bootSourceSelectComponent', {static: false}) bootSourceSelectComponent;
  rebuildOptions: IInstanceRebuildOptionsModel;
  showUserData = false;
  instanceRebuildForm = this.formBuilder.group({
    user_data: [null],
    ssh_keys: [[]],
    root_password: [''],
  });
  selectedBootSource: ISelectedBootSource | null;
  showPasswordText = false;
  backendErrors = {};
  imageRebuildId = this.activatedRoute.snapshot.queryParams.image_id || null;
  holdButtonTxt = $localize`Hold button to reveal password`;
  passwordLabel = $localize`Root password`;
  passwordHint = null;
  sshKeysHint = null;
  showPasswordInput = true;

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

  private rebuildInstance() {
    if (!this.selectedBootSource) {
      this.notificationService.showMessage($localize`You must choose a boot source!`);
      return of(null);
    }
    const value = this.instanceRebuildForm.value;
    value.image = this.selectedBootSource.object.id;
    if (value.hasOwnProperty('ssh_keys') && value.ssh_keys.length === 0) {
      delete value.ssh_keys;
    } else {
      value.ssh_keys = JSON.stringify(value.ssh_keys);
    }
    if (value.hasOwnProperty('user_data') && !value.user_data) {
      delete value.user_data;
    }
    if (!this.showPasswordInput) {
      delete value.root_password;
    }
    this.objectController.loading = true;
    this.instancesApi.rebuild(this.object.id, value).subscribe(() => {
      this.notificationService.showMessage($localize`Instance rebuild scheduled`);
      this.router.navigateByUrl(
        this.config.getPrevUrl('openstack/instances')
      ).then(() => {
      });
    }, error => {
      this.objectController.loading = false;
      this.backendErrors = error.error;
      this.formErrors.setBackendErrors(this.backendErrors);
    });
    return of(null);
  }

  public switchUserData() {
    this.showUserData = !this.showUserData;
    if (this.showUserData === false) {
      this.instanceRebuildForm.controls.user_data.setValue(null);
    }
  }

  public onBootSourceChange(selectedBootSource: ISelectedBootSource) {
    this.selectedBootSource = selectedBootSource;
    if (this.selectedBootSource?.object) {
      if (this.selectedBootSource.object?.properties &&
        this.selectedBootSource.object.properties.hasOwnProperty('fleio_default_image_username')) {
        const properties = this.selectedBootSource.object.properties as any;
        const username = properties.fleio_default_image_username;
        this.passwordLabel = $localize`Password`;
        this.passwordHint = $localize`Password will be set for user ${username}`;
        this.sshKeysHint = $localize`Keys will be set for user ${username}`;
      } else {
        this.setAuthInfoText();
      }

      this.showPasswordInput = !(this.selectedBootSource.object?.properties &&
        this.selectedBootSource.object.properties.hasOwnProperty('fleio_do_not_ask_password'));
    }
  }

  setAuthInfoText() {
    this.passwordLabel = $localize`Root password`;
    this.passwordHint = null;
    this.sshKeysHint = null;
  }

  ngOnInit() {
    if (this.objectController) {
      this.objectController.actionCallback = () => this.rebuildInstance();
    }
    this.rebuildOptions = this.activatedRoute.snapshot.data.rebuildOptions as IInstanceRebuildOptionsModel;
    if (this.imageRebuildId) {
      const imagesArray = [
        this.rebuildOptions.bootSources.image,
        this.rebuildOptions.bootSources.owned_image,
        this.rebuildOptions.bootSources.shared_image,
      ];
      this.selectedBootSource = this.bootSourceSelectComponent.initBootSource(imagesArray);
    }
  }
}
