import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, 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 { IPortModel } from '@fleio-api/openstack/model/port.model';
import { PortsApiService } from '@fleio-api/openstack/port/ports-api.service';
import { NetworksApiService } from '@fleio-api/openstack/network/networks-api.service';
import { IPortCreateOptionsModel } from '@fleio-api/openstack/model/port-create-options.model';
import { NotificationService } from '@shared/ui-api/notification.service';
import { INetworkModel } from '@fleio-api/openstack/model/network.model';

@Component({
  selector: 'app-port-create-form',
  templateUrl: './port-create-form.component.html',
  styleUrls: ['./port-create-form.component.scss']
})
export class PortCreateFormComponent extends DetailsFormBase<IPortModel> implements OnInit {
  portForm = this.formBuilder.group({
    name: [''],
    admin_state_up: [true],
    network: ['', Validators.required],
    ip_address_or_subnet: [''],
    subnet: ['', Validators.required],
    selected_fixed_ip_address: [''],
    mac_address: [''],
    port_security_enabled: [true],
    auto_add_security_group: [true],
    vnic_type: [''],
    host_id: [''],
    description: [''],
    fixed_ips: [null],
  });
  createOptions: IPortCreateOptionsModel;
  selectClient = false;
  createInClientProject = true;
  networkSelectedPlaceholder = $localize`Network`;
  networkUnselectedPlaceholder = $localize`Select network ...`;

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

  networkDisplayFn(network: INetworkModel) {
    if (!network) {
      return '';
    }
    return `${network.name} - ${network.id} - ${network.region}`;
  }

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

  ngOnInit() {
    super.ngOnInit();
    if (this.config.authService.feature('ui.openstack.ports.project')) {
      this.selectClient = true;
      this.portForm.addControl('client', this.formBuilder.control('', Validators.required));
    }
    if (this.objectController) {
      this.objectController.actionCallback = () => this.portActions();
      if (this.objectController.additionalObjects) {
        this.createOptions = this.objectController.additionalObjects.createOptions as IPortCreateOptionsModel;
      }
    }

    this.portForm.controls.ip_address_or_subnet.valueChanges.subscribe(value => {
      this.ipAddressOrSubnetUpdated(value);
    });

    if (this.createOptions) {
      this.portForm.controls.vnic_type.setValue(this.createOptions.vnic_types[0][0]);
    }

    this.ipAddressOrSubnetUpdated(this.portForm.controls.ip_address_or_subnet.value);
  }

  ipAddressOrSubnetUpdated(value) {
    if (value === 'fixed_ip_address') {
      this.portForm.controls.selected_fixed_ip_address.enable();
    } else {
      this.portForm.controls.selected_fixed_ip_address.disable();
    }
    if (value === 'subnet') {
      this.portForm.controls.subnet.enable();
    } else {
      this.portForm.controls.subnet.disable();
    }
  }

  portActions(): Observable<IActionResult> {
    this.portForm.controls.fixed_ips.setErrors(null);
    const value = this.portForm.value as any;

    value.fixed_ips = [];
    if (value.ip_address_or_subnet === 'fixed_ip_address') {
      value.fixed_ips.push({
        ip_address: value.selected_fixed_ip_address
      });
    } else if (value.ip_address_or_subnet === 'subnet') {
      value.fixed_ips.push({
        subnet_id: value.subnet.id
      });
    }

    if (!value.fixed_ips) {
      value.fixed_ips = '';
    }

    if (this.selectClient && value.client && value.client.id) {
      value.client = value.client.id;
    }

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

    if (value.network && value.network.id) {
      value.network = value.network.id;
    }

    this.createOrUpdate(
      this.portsApiService,
      value,
      true
    ).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`Port created`);
        this.redirectAfterCreate('openstack/ports', this.router, this.config);
      }, error: error => {
        if (error?.error?.fixed_ips) {
          this.portForm.controls.selected_fixed_ip_address.markAsTouched();
          this.portForm.controls.selected_fixed_ip_address.setErrors({
            backend: true,
            fleio_error: error.error.fixed_ips[0].ip_address,
          });
        }
      }
    });

    return of(null);
  }
}
