import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormArray, UntypedFormBuilder, Validators } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { VolumeTypesApiService } from '@fleio-api/openstack/volume/volume-types-api.service';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IVolumeType } from '@fleio-api/openstack/model/volume-type.model';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { IRegionModel } from '@fleio-api/openstack/model/region.model';

@Component({
  selector: 'app-volume-type-edit-form',
  templateUrl: './volume-type-edit-form.component.html',
  styleUrls: ['./volume-type-edit-form.component.scss']
})
export class VolumeTypeEditFormComponent extends DetailsFormBase<IVolumeType> implements OnInit {
  volumeTypeForm = this.formBuilder.group({
    region_name: ['', Validators.required],
    name: ['', Validators.required],
    description: [''],
    is_public: [true],
  });
  extraSpecs: UntypedFormArray;
  regions: FleioObjectsList<IRegionModel>;
  removedExtraSpecs = null;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private router: Router,
    private config: ConfigService,
    private volumeTypesApiService: VolumeTypesApiService,
    private notificationService: NotificationService,
  ) {
    super();
  }

  addProperty(key: string = '', value: string = '', keyFixed=false) {
    this.extraSpecs.push(
      this.formBuilder.group({
        key: [{value: key, disabled: keyFixed}, Validators.required],
        value: [value, Validators.required],
      })
    );
  }

  deleteProperty(index: number) {
    if (!this.removedExtraSpecs) {
      this.removedExtraSpecs = [];
    }
    // workaround for when it's disabled
    const relatedKey = this.volumeTypeForm.getRawValue().extra_specs[index].key;
    this.removedExtraSpecs.push(relatedKey);
    this.extraSpecs.removeAt(index);
  }

  changeDestination(value) {
    // createInClientProject
    if (value === false) {
      this.volumeTypeForm.controls.client.setValue('');
      this.volumeTypeForm.controls.client.clearValidators();
      this.volumeTypeForm.controls.client.reset();
    } else {
      this.volumeTypeForm.controls.client.setValidators(Validators.required);
    }
  }

  ngOnInit(): void {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.save();
      this.regions = this.objectController.additionalObjects?.regions;
    }

    if (this.object && this.object.id) {
      this.volumeTypeForm.removeControl('region_name');
      this.volumeTypeForm.patchValue(this.object);
      this.volumeTypeForm.addControl('extra_specs', this.formBuilder.array([]));
      this.extraSpecs = this.volumeTypeForm.controls.extra_specs as UntypedFormArray;
      for (const extraSpecKey in this.object.extra_specs) {
        if (this.object.extra_specs.hasOwnProperty(extraSpecKey)) {
          this.addProperty(extraSpecKey, this.object.extra_specs[extraSpecKey], true);
        }
      }
    }
  }

  save(): Observable<IActionResult> {
    const value = this.volumeTypeForm.value as any;

    if (this.extraSpecs) {
      const extraSpecsObject = {};
      const extraSpecs = this.extraSpecs.getRawValue();
      for (const extraSpec of extraSpecs) {
        extraSpecsObject[extraSpec.key] = extraSpec.value;
      }
      value.extra_specs = extraSpecsObject;
    }

    if (this.removedExtraSpecs) {
      value.deleted_extra_specs = this.removedExtraSpecs;
    }

    this.createOrUpdate(
      this.volumeTypesApiService,
      value,
    ).subscribe(() => {
      this.redirectAfterCreate('openstack/volume-types', this.router, this.config);
      this.notificationService.showMessage($localize`Volume type saved`);
    });
    return of(null);
  }

}
