import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, 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 { ILBListenerModel } from '@fleio-api/openstack/load-balancing/model/lb-listener.model';
import { LBListenersApiService } from '@fleio-api/openstack/load-balancing/listeners/lb-listeners-api.service';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { ILBPoolModel } from '@fleio-api/openstack/load-balancing/model/lb-pool.model';

@Component({
  selector: 'app-listener-edit-form',
  templateUrl: './listener-edit-form.component.html',
  styleUrls: ['./listener-edit-form.component.scss']
})
export class ListenerEditFormComponent extends DetailsFormBase<ILBListenerModel> implements OnInit {
  pools: FleioObjectsList<ILBPoolModel>;
  get loadBalancerId(): FleioId {
    return this.activatedRoute.snapshot.params.loadBalancerId;
  }

  listenerForm = this.formBuilder.group({
    name: ['', Validators.required],
    description: [''],
    admin_state_up: [''],
    timeout_client_data: [50000, Validators.min(0)],
    timeout_tcp_inspect: [0, Validators.min(0)],
    timeout_member_connect: [5000, Validators.min(0)],
    timeout_member_data: [50000, Validators.min(0)],
    connection_limit: [-1, Validators.min(-1)],
    default_pool_id: [''],
  });
  loading = false;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private lbListenersApiService: LBListenersApiService,
    private router: Router,
    private config: ConfigService,
    public clipboard: ClipboardService,
    private activatedRoute: ActivatedRoute,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveListener();
      this.pools = this.objectController.additionalObjects.pools;
    }
    if (this.object && this.object.id) {
      this.listenerForm.patchValue(this.object);
    }
  }

  saveListener(): Observable<IActionResult> {
    const value = this.listenerForm.value;
    this.loading = true;
    this.createOrUpdate(
      this.lbListenersApiService,
      value,
    ).subscribe(() => {
      this.router.navigate(
        [
          this.config.getPanelUrl(
            `openstack/load-balancers/${this.loadBalancerId}`,
          )
        ], {
          fragment: 'listeners',
          queryParamsHandling: 'merge',
        }
      );
    }).add(() => {
      this.loading = false;
    });

    return of(null);
  }
}
