import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
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 { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { ILBMemberModel } from '@fleio-api/openstack/load-balancing/model/lb-member.model';
import { ILBMemberCreateOptionsModel } from '@fleio-api/openstack/load-balancing/model/lb-member-create-options.model';
import { LBMembersApiService } from '@fleio-api/openstack/load-balancing/members/lb-members-api.service';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-member-edit-form',
  templateUrl: './member-edit-form.component.html',
  styleUrls: ['./member-edit-form.component.scss'],
  providers: [LBMembersApiService],
})
export class MemberEditFormComponent extends DetailsFormBase<ILBMemberModel> implements OnInit {
  get loadBalancerId(): FleioId {
    return this.activatedRoute.snapshot.params.loadBalancerId;
  }

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


  memberForm = this.formBuilder.group({
    name: ['',],
    address: [''],
    protocol_port: [],
    weight: [1, [ValidatorsHelper.requiredNumericValueValidator, Validators.min(1)]],
    monitor_address: [''],
    monitor_port: [null, Validators.min(1)],
    admin_state_up: [true],
    backup: [true],
  });
  loading = false;
  createOptions: ILBMemberCreateOptionsModel;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private lbMembersApiService: LBMembersApiService,
    private router: Router,
    private config: ConfigService,
    private activatedRoute: ActivatedRoute,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.lbMembersApiService.setAdditionalQueryParams({pool_id: this.poolId});
      this.objectController.actionCallback = () => this.saveMember();
      this.createOptions = this.objectController.additionalObjects.createOptions;
    }
    if (this.object && this.object.id) {
      this.memberForm.patchValue(this.object);
      this.memberForm.controls.address.disable();
      this.memberForm.controls.protocol_port.disable();
    }
  }

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

    return of(null);
  }
}

