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, UntypedFormControl } 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 { ILBHealthMonitorModel } from '@fleio-api/openstack/load-balancing/model/lb-health-monitor.model';
import { LBHealthMonitorsApiService } from '@fleio-api/openstack/load-balancing/health-monitors/lb-health-monitors-api.service';
import { ILBHealthMonitorCreateOptionsModel } from '@fleio-api/openstack/load-balancing/model/lb-health-monitor-create-options.model';
import { MonitorFormHelper } from '../monitor-form-helper';

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

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

  monitorForm = new MonitorFormHelper(this.formBuilder).getMonitorForm();
  loading = false;
  createOptions: ILBHealthMonitorCreateOptionsModel;

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

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.lbHealthMonitorsApiService.setAdditionalQueryParams({pool_id: this.poolId});
      this.objectController.actionCallback = () => this.saveMonitor();
      this.createOptions = this.objectController.additionalObjects.createOptions;
    }

    this.monitorForm.controls.type.valueChanges.subscribe(value => {
      if (!['HTTP', 'HTTPS'].includes(value)) {
        this.monitorForm.removeControl('http_method');
        this.monitorForm.removeControl('expected_codes');
        this.monitorForm.removeControl('url_path');
      } else {
        this.monitorForm.addControl('http_method', new UntypedFormControl('GET'));
        this.monitorForm.addControl('expected_codes', new UntypedFormControl('200'));
        this.monitorForm.addControl('url_path', new UntypedFormControl('/'));
      }
    });
    if (this.object && this.object.id) {
      this.monitorForm.patchValue(this.object);
      this.monitorForm.controls.type.disable();
    }
  }

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

    return of(null);
  }
}

