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

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

  @Input() service: Service;
  pingWaiting: boolean;
  pingResult: PingResult;

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

  doPing() {
    this.pingWaiting = true;


    const option = {
      Retry: 3,
      Interval: 1,
      Deadline: 1,
    };

    this.probeService
      .call<PingResult>('PingService.PingService', this.service, option)
      .pipe(
        map((pingResult: PingResult) => {
          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();
  }

}
