import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { INetworkModel } from '@fleio-api/openstack/model/network.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { INetworkCreateOptionsModel } from '@fleio-api/openstack/network/model/network-create-options.model';
import { NetworksApiService } from '@fleio-api/openstack/network/networks-api.service';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';

@Component({
  selector: 'app-network-auto-create-form',
  templateUrl: './network-auto-create-form.component.html',
  styleUrls: ['./network-auto-create-form.component.scss']
})
export class NetworkAutoCreateFormComponent extends DetailsFormBase<INetworkModel> implements OnInit {
  networkForm = this.formBuilder.group({
    region: ['', Validators.required],
  });
  createOptions: INetworkCreateOptionsModel;
  clientField = false;

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

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.networksActions();
      this.createOptions = this.objectController.additionalObjects.createOptions as INetworkCreateOptionsModel;
      this.networkForm.controls.region.setValue(this.createOptions.selected_region);
    }

    if (this.authSvc.feature('ui.openstack.networks.auto-create.client-field')) {
      this.networkForm.addControl('client', this.formBuilder.control('', Validators.required));
      this.clientField = true;
    }
  }

  networksActions(): Observable<IActionResult> {
    const value = this.networkForm.value;

    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return of(null);
    }

    const request = this.networksApiService.autoCreateNetwork(
      this.clientField ? value.client.id : null, value.region,
    );

    this.objectController.loading = true;
    request.subscribe(() => {
      this.notificationService.showMessage($localize`Network created`);
      const url = this.config.getPanelUrl('openstack/networks');
      this.router.navigateByUrl(
        url
      ).catch(() => {
      });
      return null;
    }, error => {
      this.objectController.loading = false;
      if (error.error) {
        this.setErrors(error.error);
      }
    });

    return of(null);
  }
}
