import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormArray, UntypedFormBuilder, UntypedFormControl, Validators } from '@angular/forms';
import { 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 { ISubnetPoolModel } from '@fleio-api/openstack/subnet-pools/model/subnet-pool.model';
import { SubnetPoolsApiService } from '@fleio-api/openstack/subnet-pools/subnet-pools-api.service';
import { ISubnetPoolCreateOptionsModel } from '@fleio-api/openstack/subnet-pools/model/subnet-pool-create-options.model';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-subnet-pool-edit-form',
  templateUrl: './subnet-pool-edit-form.component.html',
  styleUrls: ['./subnet-pool-edit-form.component.scss']
})
export class SubnetPoolEditFormComponent extends DetailsFormBase<ISubnetPoolModel> implements OnInit {
  subnetPoolForm = this.formBuilder.group({
    region: ['', Validators.required],
    name: ['', Validators.required],
    description: [''],
    default_prefixlen: [24, ValidatorsHelper.requiredIntegerValidator],
    min_prefixlen: [24, ValidatorsHelper.requiredIntegerValidator],
    max_prefixlen: [24, ValidatorsHelper.requiredIntegerValidator],
    default_quota: [],
    shared: [false],
    is_default: [false],
    prefixes: this.formBuilder.array([]),
  });
  createOptions: ISubnetPoolCreateOptionsModel;
  createInClientProject = true;
  selectClient = false;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private subnetPoolsApiService: SubnetPoolsApiService,
    private router: Router,
    private config: ConfigService,
    private clientsApiService: ClientsApiService,
    private notificationService: NotificationService,
  ) {
    super();
  }

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

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.subnetPoolActions();
      this.createOptions = this.objectController.additionalObjects.createOptions;
    }

    if (!this.object.id) {
      this.selectClient = true;
      this.subnetPoolForm.addControl('client', this.formBuilder.control('', Validators.required));
    }

    if (this.object && this.object.id) {
      for (const prefix of this.object.prefixes) {
        this.prefixes.push(new UntypedFormControl('', Validators.required));
      }
      this.subnetPoolForm.patchValue(this.object);
    } else {
      if (this.createOptions) {
        this.subnetPoolForm.controls.region.setValue(this.createOptions.selected_region);
      }
      this.prefixes.push(new UntypedFormControl('', Validators.required));
    }
  }

  subnetPoolActions(): Observable<IActionResult> {
    const value = this.subnetPoolForm.value as any;
    if (value.client && value.client.id) {
      value.client = value.client.id;
    }

    if (!this.object.id && !this.createInClientProject) {
      value.create_as_admin = true;
    }

    this.createOrUpdate(
      this.subnetPoolsApiService,
      value,
    ).subscribe(() => {
      this.notificationService.showMessage($localize`Subnet pool saved`);
      this.redirectAfterCreate('openstack/subnet-pools', this.router, this.config);
    });

    return of(null);
  }

  get prefixes(): UntypedFormArray {
    return this.subnetPoolForm.controls.prefixes as UntypedFormArray;
  }

  addPrefix(event: PointerEvent) {
    event.preventDefault();
    this.prefixes.push(new UntypedFormControl('', Validators.required));
  }

  deletePrefix(index: number) {
    this.prefixes.removeAt(index);
  }
}
