import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges, OnInit } from '@angular/core';
import { ProbeHost, Probe } from '@overflow/commons-typescript/model/probe';
import { Store, select } from '@ngrx/store';
import { Observable, of, Subscription } from 'rxjs';
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 { ProbeHostService } from '../service/probe-host.service';


@Component({
  selector: 'of-probe-selector',
  templateUrl: './probe-selector.component.html',
})
export class ProbeSelectorComponent implements OnInit, OnChanges {

  @Input() probeHostID: number;
  probeHosts: ProbeHost[];
  pending$: Observable<boolean>;
  error$: Observable<any>;
  @Output() select = new EventEmitter<ProbeHost>();

  options: Probe[];
  selected: Probe;

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

  ) {
  }

  ngOnInit() {
    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;
            }),
            catchError(error => {
              this.error$ = of(error);
              return of();
            })
          )
      ),
      tap(() => {
        this.generate();
        this.pending$ = of(false);
      }),
      take(1),
    ).subscribe();
  }

  ngOnChanges(changes: SimpleChanges): void {

  }

  generate() {
    this.checkPreselected();
    this.options = [];
    for (const ph of this.probeHosts) {
      this.options.push(ph.probe);
    }
  }

  checkPreselected() {
    if (!this.probeHosts || !this.probeHostID) {
      return;
    }
    setTimeout(() => {
      const preselected = this.probeHosts.find(probeHost => probeHost.id === Number(this.probeHostID));
      this.select.emit(preselected);
    });
  }

  onSelect() {
    const optionselected = this.probeHosts.find(probeHost => probeHost.probe.id === this.selected.id);
    this.select.emit(optionselected);
  }

}
