import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
import { ProbeHost, Probe } from '@overflow/commons-typescript/model/probe';

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

  @Output() select = new EventEmitter<ProbeHost>();
  @Input() probeHosts: ProbeHost[];
  @Input() probeHostID: number;

  options: Probe[];
  selected: Probe;

  constructor() {
  }

  ngOnChanges(changes: SimpleChanges): void {
    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);
  }

}
