import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ILBCreateOptionsModel } from '@fleio-api/openstack/load-balancing/model/lb-create-options.model';
import { Observable, of } from 'rxjs';
import { IInstanceModel } from '@fleio-api/openstack/model/instance.model';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { ClipboardService } from '@shared/ui-api/clipboard.service';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { debounceTime, map, mergeMap, startWith } from 'rxjs/operators';
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 { IStepDetails } from '../../../step-details';
import { MonitorFormHelper } from '../../../lb-pools/tabs/monitor-form-helper';

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

  listenerDetails = this.formBuilder.group({
    name: ['',],
    description: [''],
    protocol: ['', Validators.required],
    protocol_port: [null, [Validators.min(1), Validators.max(65535)]],
    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)],
    x_forwarded_for: [false],
    x_forwarded_port: [false],
    x_forwarded_proto: [false],
    x_ssl_client_verify: [false],
    x_ssl_client_has_cert: [false],
    x_ssl_client_dn: [false],
    x_ssl_client_cn: [false],
    x_ssl_issuer: [false],
    x_ssl_client_sha1: [false],
    x_ssl_client_not_before: [false],
    x_ssl_client_not_after: [false],
    admin_state_up: [true],
    default_tls_container_ref: [null, Validators.required],
    tls_ciphers: [],
  });
  sessionPersistence = this.formBuilder.group({
    type: [''],
    cookie_name: ['', Validators.required],
  });
  poolDetails = this.formBuilder.group({
    name: ['', Validators.required],
    description: [''],
    lb_algorithm: ['', Validators.required],
    session_persistence: this.sessionPersistence,
    admin_state_up: [true],
  });
  poolMembers = this.formBuilder.array([]);
  monitorDetails = new MonitorFormHelper(this.formBuilder).getMonitorForm();
  listenerForm = this.formBuilder.group({
    listener_details: this.listenerDetails,
    pool_details: this.poolDetails,
    pool_members: this.poolMembers,
    monitor_details: this.monitorDetails,
  });
  searchInstances = this.formBuilder.group({
    search: [''],
  });

  loading = false;
  steps: { [stepNo: number]: IStepDetails } = {
    1: {
      name: $localize`Listener details`,
      valid: false,
      selected: true,
      formControl: this.listenerDetails,
    },
    2: {
      name: $localize`Pool details`,
      valid: false,
      selected: false,
      formControl: this.poolDetails,
    },
    3: {
      name: $localize`Pool members`,
      valid: true,
      selected: false,
      formControl: this.poolMembers,
    },
    4: {
      name: $localize`Monitor details`,
      valid: false,
      selected: false,
      formControl: this.monitorDetails,
    },
  };
  activeStep = 1;
  createOptions: ILBCreateOptionsModel;
  filteredInstances$: Observable<IInstanceModel[]>;

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

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = (action: IAction) => this.listenerAction(action);
      if (this.objectController.additionalObjects) {
        this.createOptions = this.objectController.additionalObjects.createOptions;
      }
      this.updateActions();
    }

    this.listenerForm.valueChanges.subscribe(() => {
      this.steps[this.activeStep].valid = this.steps[this.activeStep].formControl.valid;
      this.updateCreateAction(this.primaryAction);
    });

    this.listenerDetails.controls.protocol.valueChanges.subscribe(value => {
      if (value === 'HTTP' && !this.listenerDetails.controls.protocol_port.value) {
        this.listenerDetails.controls.protocol_port.setValue(80);
      }

      if (['HTTPS', 'TERMINATED_HTTPS'].includes(value) && !this.listenerDetails.controls.protocol_port.value) {
        this.listenerDetails.controls.protocol_port.setValue(443);
      }

      if (value === 'TERMINATED_HTTPS') {
        this.listenerDetails.controls.default_tls_container_ref.enable();
      } else {
        this.listenerDetails.controls.default_tls_container_ref.disable();
      }
    });

    this.sessionPersistence.controls.cookie_name.disable({emitEvent: false, onlySelf: true});
    this.sessionPersistence.controls.type.valueChanges.subscribe((value) => {
      if (value !== 'APP_COOKIE') {
        this.sessionPersistence.controls.cookie_name.disable({emitEvent: false, onlySelf: true});
      } else {
        this.sessionPersistence.controls.cookie_name.enable({emitEvent: false, onlySelf: true});
      }
    });

    this.filteredInstances$ = this.searchInstances.controls.search.valueChanges.pipe(
      startWith(''),
      debounceTime(300),
      mergeMap(value => this.instancesApiService.list({
        search: value,
        openstack_project: true,
      }).pipe(map(instances => instances.objects)))
    );
  }

  updateActions() {
    for (const action of this.detailsActions) {
      switch (action.internalName) {
        case 'back':
          action.disabled = this.activeStep <= 1;
          break;
        case 'next':
          action.disabled = this.activeStep >= 4;
          break;
        case 'create':
          this.updateCreateAction(action);
          break;
      }
    }
  }

  updateCreateAction(action: IAction) {
    action.disabled = !this.listenerForm.valid;
  }

  stepChanged(stepNoStr: any) {
    const stepNo = parseInt(stepNoStr, 10);
    this.steps[this.activeStep].selected = false;
    this.activeStep = stepNo;
    this.steps[this.activeStep].selected = true;
    this.updateActions();
  }

  addExternalPoolMember() {
    this.poolMembers.push(this.formBuilder.group({
      address: ['', Validators.required],
      protocol_port: [null, [Validators.required, Validators.min(1), Validators.max(65535)]],
      subnet_id: [''],
      weight: [1, [Validators.required, Validators.min(1)]],
    }));
  }

  removePoolMember(index: number) {
    this.poolMembers.removeAt(index);
  }

  addExistingInstance(instance: IInstanceModel) {
    const subnetId = this.createOptions.subnets.find(s => s.id === instance.access_subnet_id)?.id || '';
    this.poolMembers.push(this.formBuilder.group({
      address: [instance.access_ip, Validators.required],
      protocol_port: [null, [Validators.required, Validators.min(1), Validators.max(65535)]],
      subnet_id: [subnetId],
      weight: [1, [Validators.required, Validators.min(1)]],
    }));
  }


  listenerAction(action: IAction): Observable<IActionResult> {
    switch (action.internalName) {
      case 'back':
        this.stepChanged(this.activeStep - 1);
        return of(null);
      case 'next':
        this.stepChanged(this.activeStep + 1);
        return of(null);
    }
    const value = this.listenerForm.value;
    value.loadbalancer_id = this.loadBalancerId;
    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);
  }
}
