import { Component, Input, OnChanges, SimpleChanges, ViewChildren, QueryList } 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';
import { AutoHeightDirective } from '@overflow/commons/ui/directive/auto-height.directive';

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

  @Input() service: Service;

  @ViewChildren(AutoHeightDirective) autoHeightDirectives: QueryList<AutoHeightDirective>;


  pingWaiting: boolean;
  pingResult: PingResult;
  pingResultStr: string;

  count: number;
  interval: number;
  deadline: number;


  constructor(
    private probeService: ProbeService
  ) {
    this.pingWaiting = false;
    this.count = 5;
    this.interval = 1;
    this.deadline = 1;
  }

  ngOnChanges(simpleChanges: SimpleChanges): void {
    this.pingResult = null;
  }


  doPing() {
    this.pingWaiting = true;

    const option = {
      Count: this.count,
      Interval: this.interval,
      Deadline: this.deadline,
    };

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

  onTabViewChange($event) {
    const index = String($event.index);
    this.autoHeightDirectives.map(item => {
      if (item.key === index) {
        item.forceCalculate();
      }
    });
  }

}
