import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
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 { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { of } from 'rxjs';
import { ClusterTemplatesApiService } from '@fleio-api/openstack/cluster-template/cluster-templates-api.service';

@Component({
  selector: 'app-cluster-upgrade-form',
  templateUrl: './cluster-upgrade-form.component.html',
  styleUrls: ['./cluster-upgrade-form.component.scss']
})
export class ClusterUpgradeFormComponent extends DetailsFormBase<IClusterModel> implements OnInit {
  upgradeClusterForm = this.formBuilder.group({
    cluster_template: ['', Validators.required],
  });
  clusterTemplateSelectedPlaceholder = $localize`Cluster template`;
  clusterTemplateUnselectedPlaceholder = $localize`Select cluster template ...`;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private clustersApiService: ClustersApiService,
    public clusterTemplatesApiService: ClusterTemplatesApiService,
    private router: Router,
    private config: ConfigService,
  ) {
    super();
  }

  upgradeCluster() {
    this.validate();
    if (this.upgradeClusterForm.invalid) {
      this.displayControlErrors();
      return of(null);
    }
    const value = this.upgradeClusterForm.value;
    if (value.cluster_template && value.cluster_template.id) {
      value.cluster_template = value.cluster_template.id;
    }
    this.objectController.loading = true;
    this.clustersApiService.upgradeCluster(this.object.id, value.cluster_template).subscribe(response => {
      this.router.navigateByUrl(
        this.config.getPanelUrl(`openstack/clusters/${this.object.id}`)
      ).catch(() => {
      });
    }, error => {
      this.objectController.loading = false;
      if (error.error) {
        this.setErrors(error.error);
      }
    });
    return of(null);
  }

  ngOnInit(): void {
    if (this.objectController) {
      this.objectController.actionCallback = () => this.upgradeCluster();
    }
  }
}
