import { Component, Input, OnChanges, SimpleChanges, ViewChildren, QueryList } from '@angular/core';

import { of } from 'rxjs';
import { map, catchError, take } from 'rxjs/operators';

import { Host } from '@overflow/model/discovery';
import { PingResult } from '@overflow/model/ping';

import { ProbeService } from '../service/probe.service';
import { AutoHeightDirective } from '@overflow/commons/ui/directive/auto-height.directive';


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

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


  pingWaiting: boolean;

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

  pingResult: PingResult;
  pingResultRaw: string;


  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.PingHost', this.host, option)
      .pipe(
        map((pingResult: PingResult) => {
          if (pingResult) {
            this.pingResult = pingResult;
            this.pingResultRaw = pingResult.raw.join('\r\n');
          }
          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();
      }
    });
  }

}
