import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { IFlavorModel } from '@fleio-api/openstack/model/flavor.model';
import { FlavorsApiService } from '@fleio-api/openstack/flavor/flavors-api.service';
import { ActivatedRoute, NavigationExtras, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { IFlavorCreateOptionsModel } from '@fleio-api/openstack/model/flavor-create-options.model';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-flavor-edit-form',
  templateUrl: './flavor-edit-form.component.html',
  styleUrls: ['./flavor-edit-form.component.scss']
})
export class FlavorEditFormComponent extends DetailsFormBase<IFlavorModel> implements OnInit {
  flavorForm = this.formBuilder.group({
    preserve_id: [true],
    name: ['', Validators.required],
    region: ['', Validators.required],
    memory_mb: ['', [ValidatorsHelper.requiredIntegerValidator, Validators.min(1)]],
    vcpus: [1, [ValidatorsHelper.requiredIntegerValidator, Validators.min(1)]],
    root_gb: [1, [ValidatorsHelper.requiredIntegerValidator, Validators.min(0)]],
    swap: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(0)]],
    ephemeral_gb: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(0)]],
    description: [''],
    is_public: [true],
    show_for_end_user: [true],
    use_for_dbaas: [false],
    out_of_stock: [false],
    flavor_id: [null],
  });

  newFlavor = false;

  public createOptions: IFlavorCreateOptionsModel;
  private sourceFlavorId: FleioId;

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

  ngOnInit() {
    super.ngOnInit();
    this.createOptions = this.activatedRoute.snapshot.data.createOptions;
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveFlavor();
    }

    if (this.authSvc && !this.authSvc.feature('openstack.dbaas')) {
      this.flavorForm.removeControl('use_for_dbaas');
    }

    if (this.objectController?.state === 'clone') {
      this.sourceFlavorId = this.object.id;
      this.object.id = null;
    }

    if (this.object) {
      this.flavorForm.patchValue(this.object);
    }

    if (this.object && !this.object.id) {
      // creating new flavor
      this.newFlavor = true;
      if (this.objectController?.state !== 'clone') {
        this.flavorForm.controls.region.setValue(this.createOptions.selected_region);
      }
    }
  }

  protected initTabData() {
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveFlavor();
    }
  }

  saveFlavor(): Observable<IActionResult> {
    const value = this.flavorForm.value;

    if (this.objectController?.state === 'clone') {
      value.source_flavor_id = this.sourceFlavorId;
    }

    this.createOrUpdate(
      this.flavorsApi,
      value,
      true
    ).subscribe((response: any) => {
      if (this.newFlavor) {
        this.redirectAfterCreate('openstack/flavors', this.router, this.config);
      } else {
        let id = this.object.id;
        if (response && response.id) {
          id = response.id;
        }
        this.router.navigateByUrl(
          this.config.getPanelUrl(`openstack/flavors/${id}`)
        ).catch(() => {
        });
      }
    });

    return of(null);
  }
}
