import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { ILBPoolModel } from '@fleio-api/openstack/load-balancing/model/lb-pool.model';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
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 { LBPoolsApiService } from '@fleio-api/openstack/load-balancing/pools/lb-pools-api.service';
import { ILBPoolCreateOptionsModel } from '@fleio-api/openstack/load-balancing/model/lb-pool-create-options.model';

@Component({
  selector: 'app-pool-edit-form',
  templateUrl: './pool-edit-form.component.html',
  styleUrls: ['./pool-edit-form.component.scss']
})
export class PoolEditFormComponent extends DetailsFormBase<ILBPoolModel> implements OnInit {
  createOptions: ILBPoolCreateOptionsModel;

  get loadBalancerId(): FleioId {
    return this.activatedRoute.snapshot.params.loadBalancerId;
  }

  get listenerId(): FleioId {
    return this.activatedRoute.snapshot.queryParams.listenerId;
  }

  poolForm = this.formBuilder.group({
    name: ['', Validators.required],
    description: [''],
    admin_state_up: [''],
    lb_algorithm: ['', Validators.required],
    session_persistence: this.formBuilder.group({
      type: [''],
      cookie_name: [''],
    }),
  });
  loading = false;

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

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.savePool();
      this.createOptions = this.objectController.additionalObjects.createOptions;
    }
    if (this.object && this.object.id) {
      const obj = this.object;
      if (!obj.session_persistence) {
        obj.session_persistence = {};
      }
      this.poolForm.patchValue(this.object);
    }
  }

  savePool(): Observable<IActionResult> {
    const value = this.poolForm.value;
    this.loading = true;
    this.createOrUpdate(
      this.lbPoolsApiService,
      value,
    ).subscribe(() => {
      let redirectFragment = `openstack/load-balancers/${this.loadBalancerId}`;
      if (this.listenerId) {
        redirectFragment += `/listeners/${this.listenerId}`;
      }
      this.router.navigate(
        [
          this.config.getPanelUrl(
            redirectFragment,
          )
        ], {
          fragment: 'pools',
          queryParamsHandling: 'merge',
        }
      );
    }).add(() => {
      this.loading = false;
    });

    return of(null);
  }
}
