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 { 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 { IStepDetails } from '../../../step-details';
import { ILBPoolModel } from '@fleio-api/openstack/load-balancing/model/lb-pool.model';
import { LBPoolsApiService } from '@fleio-api/openstack/load-balancing/pools/lb-pools-api.service';
import { MonitorFormHelper } from '../monitor-form-helper';

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

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

  sessionPersistence = this.formBuilder.group({
    type: [''],
    cookie_name: ['', Validators.required],
  });
  poolDetails = this.formBuilder.group({
    name: ['', Validators.required],
    protocol: ['', 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();
  poolForm = this.formBuilder.group({
    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`Pool details`,
      valid: false,
      selected: true,
      formControl: this.poolDetails,
    },
    2: {
      name: $localize`Pool members`,
      valid: true,
      selected: false,
      formControl: this.poolMembers,
    },
    3: {
      name: $localize`Monitor details`,
      valid: false,
      selected: false,
      formControl: this.monitorDetails,
    },
  };
  activeStep = 1;
  createOptions: ILBCreateOptionsModel;
  filteredInstances$: Observable<IInstanceModel[]>;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private lbPoolsApiService: LBPoolsApiService,
    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.poolAction(action);
      if (this.objectController.additionalObjects) {
        this.createOptions = this.objectController.additionalObjects.createOptions;
      }
      this.updateActions();
    }

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

    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 >= 3;
          break;
        case 'create':
          this.updateCreateAction(action);
          break;
      }
    }
  }

  updateCreateAction(action: IAction) {
    action.disabled = !this.poolForm.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)]],
    }));
  }


  poolAction(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.poolForm.value;
    value.loadbalancer_id = this.loadBalancerId;
    value.listener_id = this.listenerId;
    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);
  }
}
