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 { ClipboardService } from '@shared/ui-api/clipboard.service';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { ILoadBalancerModel } from '@fleio-api/openstack/load-balancing/model/load-balancer.model';
import { LoadBalancersApiService } from '@fleio-api/openstack/load-balancing/load-balancers/load-balancers-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-load-balancer-edit-form',
  templateUrl: './load-balancer-edit-form.component.html',
  styleUrls: ['./load-balancer-edit-form.component.scss']
})
export class LoadBalancerEditFormComponent extends DetailsFormBase<ILoadBalancerModel> implements OnInit {
  loadBalancerForm = this.formBuilder.group({
    name: ['', Validators.required],
    description: [''],
    admin_state_up: [''],
  });

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

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveLoadBalancer();
    }
    if (this.object && this.object.id) {
      this.loadBalancerForm.patchValue(this.object);
    }
  }

  saveLoadBalancer(): Observable<IActionResult> {
    const value = this.loadBalancerForm.value;
    this.createOrUpdate(
      this.loadBalancersApiService,
      value,
    ).subscribe(() => {
      this.notificationService.showMessage($localize`Load balancer saved`);
      const parsedUrl = this.router.parseUrl(this.config.getPrevUrl('openstack/load-balancers'));
      parsedUrl.queryParams = {};
      this.router.navigate([decodeURI(parsedUrl.toString())], {queryParamsHandling: 'merge'},
      ).catch(() => {
      });
    });

    return of(null);
  }
}
