import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Host } from '@overflow/model/discovery';
import { ProbeService } from '../service/probe.service';
import { map, catchError, take } from 'rxjs/operators';
import { PingResult } from '@overflow/model/ping';
import { of } from 'rxjs';


@Component({
  selector: 'app-host-detail',
  templateUrl: './host-detail.component.html',
  styleUrls: ['./host-detail.component.scss'],
})
export class HostDetailComponent {

  @Input() host: Host;

  healthResponse: string;

  pingWaiting: boolean;
  pingResult: PingResult;
  retries: number;

  constructor(
    private probeService: ProbeService,
  ) {
    this.pingWaiting = false;
    this.retries = 5;
  }

  doPing() {
    this.pingWaiting = true;
    this.pingWaiting = true;

    const option = {
      Retry: this.retries,
      Interval: 1,
      Deadline: 1,
    };

    this.probeService
      .call<PingResult>('PingService.PingHost', this.host, option)
      .pipe(
        map((pingResult: PingResult) => {
          this.healthResponse = 'aslkdfjas\nasdflskjdf';
          if (pingResult) {
            this.pingResult = pingResult;
          }
          this.pingWaiting = false;
        }),
        catchError(error => {
          console.log(error);
          alert('An error has occurred.');
          this.pingWaiting = false;
          return of();
        }),
        take(1)
      )
      .subscribe();
  }

}
