import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { ILoadBalancerModel } from '@fleio-api/openstack/load-balancing/model/load-balancer.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { LoadBalancersApiService } from '@fleio-api/openstack/load-balancing/load-balancers/load-balancers-api.service';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { EMPTY, Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { ILBAssociateFloatingIpOptions } from '@fleio-api/openstack/load-balancing/model/lb-associate-floating-ip-options.model';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-load-balancer-associate-floating-ip-form',
  templateUrl: './load-balancer-associate-floating-ip-form.component.html',
  styleUrls: ['./load-balancer-associate-floating-ip-form.component.scss']
})
export class LoadBalancerAssociateFloatingIpFormComponent
  extends DetailsFormBase<ILoadBalancerModel> implements OnInit {
  associateFloatingIpForm = this.formBuilder.group({
    ip: ['', Validators.required],
  });
  associateFloatingIpOptions: ILBAssociateFloatingIpOptions;

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

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.associateFloatingIp();
      if (this.objectController.additionalObjects) {
        this.associateFloatingIpOptions = this.objectController.additionalObjects.associateFloatingIpOptions;
        if (!this.associateFloatingIpOptions || this.associateFloatingIpOptions.available_ips.length === 0) {
          this.primaryAction.disabled = true;
        }
      }
    }
  }

  associateFloatingIp(): Observable<IActionResult> {
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return EMPTY;
    }

    const value = this.associateFloatingIpForm.value;
    this.objectController.loading = true;
    this.loadBalancersApiService.associateFloatingIp(this.object.id, value).subscribe(() => {
      this.notificationService.showMessage($localize`Floating IP associated.`);
      const parsedUrl = this.router.parseUrl(this.config.getPrevUrl('openstack/load-balancers'));
      parsedUrl.queryParams = {};
      this.router.navigate([decodeURI(parsedUrl.toString())], {queryParamsHandling: 'merge'},
      ).catch(() => {
      });
    }, (error) => {
      this.objectController.loading = false;
      if (error.error) {
        this.setErrors(error.error);
      }
    });

    return of(null);
  }
}
