import {
  Component, OnInit, EventEmitter, Output,
} from '@angular/core';
import { ProbeHostService } from '@overflow/probe/service/probe-host.service';
import { Store, select } from '@ngrx/store';
import { catchError, exhaustMap, map, tap, take } from 'rxjs/operators';
import { AuthSelector } from '@overflow/shared/auth/store';
import { DomainMember } from '@overflow/commons-typescript/model/domain';
import { Observable, Subscription, of } from 'rxjs';
import { ProbeHost } from '@overflow/commons-typescript/model/probe';
import { MenuItem } from 'primeng/primeng';


@Component({
  selector: 'of-infra-map',
  templateUrl: './infra-map.component.html',
  providers: [
    ProbeHostService
  ]
})
export class InfraMapComponent implements OnInit {

  pending$: Observable<boolean>;
  error$: Observable<any>;

  tabs: MenuItem[];
  probeHosts: ProbeHost[];
  probeTabIdx: number;

  selectedProbeHost: ProbeHost;

  @Output() discovery = new EventEmitter();

  constructor(
    private store: Store<any>,
    private probeHostService: ProbeHostService,
  ) {
  }

  ngOnInit(): void {
    this.getProbes();
  }

  getProbes() {
    this.store.pipe(
      tap(() => {
        this.pending$ = of(true);
      }),
      select(AuthSelector.selectDomainMember),
      exhaustMap((domainMember: DomainMember) =>
        this.probeHostService.readAllByDomainID(domainMember.domain.id)
          .pipe(
            map((probeHosts: ProbeHost[]) => {
              this.probeHosts = probeHosts;
              this.generateTabs();
            }),
            catchError(error => {
              this.error$ = of(error);
              return of();
            })
          )
      ),
      tap(() => {
        this.pending$ = of(false);
      }),
      take(1),
    ).subscribe();
  }

  generateTabs() {
    this.tabs = [];
    this.probeHosts.forEach((ph, i) => {
      this.tabs.push({
        label: ph.probe.cidr
      });
    });
    this.selectedProbeHost = this.probeHosts[0];
  }

  onProbeChange(event) {
    this.selectedProbeHost = this.probeHosts[event.index];
  }

}
