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 { ClipboardService } from '@shared/ui-api/clipboard.service';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { ILBPolicyModel } from '@fleio-api/openstack/load-balancing/model/lb-policy.model';
import { LBPoliciesApiService } from '@fleio-api/openstack/load-balancing/policies/lb-policies-api.service';
import { ILBPolicyCreateOptionsModel } from '@fleio-api/openstack/load-balancing/model/lb-policy-create-options.model';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { ILBPoolModel } from '@fleio-api/openstack/load-balancing/model/lb-pool.model';

@Component({
  selector: 'app-policy-edit-form',
  templateUrl: './policy-edit-form.component.html',
  styleUrls: ['./policy-edit-form.component.scss'],
})
export class PolicyEditFormComponent extends DetailsFormBase<ILBPolicyModel> implements OnInit {
  createOptions: ILBPolicyCreateOptionsModel;
  pools: FleioObjectsList<ILBPoolModel>;

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

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

  policyForm = this.formBuilder.group({
    name: [''],
    description: [''],
    action: ['', Validators.required],
    redirect_url: ['', Validators.required],
    redirect_pool_id: ['', Validators.required],
    position: [null],
    admin_state_up: [false],
  });
  loading = false;

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

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.savePolicy();
      this.createOptions = this.objectController.additionalObjects.createOptions;
      this.pools = this.objectController.additionalObjects.pools;
    }

    this.policyForm.controls.redirect_pool_id.disable();
    this.policyForm.controls.redirect_url.disable();

    this.policyForm.controls.action.valueChanges.subscribe(value => {
      switch (value) {
        case 'REDIRECT_TO_POOL':
          this.policyForm.controls.redirect_pool_id.enable();
          this.policyForm.controls.redirect_url.disable();
          break;
        case 'REDIRECT_TO_URL':
          this.policyForm.controls.redirect_pool_id.disable();
          this.policyForm.controls.redirect_url.enable();
          break;
        case 'REJECT':
          this.policyForm.controls.redirect_pool_id.disable();
          this.policyForm.controls.redirect_url.disable();
          break;
      }
    });

    if (this.object && this.object.id) {
      this.policyForm.patchValue(this.object);
    }
  }

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

    return of(null);
  }
}
