import { Component, OnInit, AfterContentInit, Input, OnChanges } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { RPCClientError } from '@loafer/ng-rpc/protocol';

import * as DetailStore from 'packages/probe/store/probe-host';
import { ProbeHostSelector } from 'packages/probe/store';
import { Probe, ProbeHost } from 'packages/probe/model';


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

  @Input() probe: Probe;
  @Input() visible: boolean;

  probeHost$ = this.detailStore.pipe(select(ProbeHostSelector.select('probeHost')));
  probeHost: ProbeHost;

  constructor(
    private detailStore: Store<DetailStore.State>,
  ) { }

  ngOnInit() {
    this.probeHost$.subscribe(
      (probeHost: ProbeHost) => {
        if (probeHost) {
          this.probe = probeHost;
        }
      },
      (error: RPCClientError) => {
        console.log(error.response.message);
      }
    );
  }

  ngAfterContentInit() {
    this.detailStore.dispatch(
      new DetailStore.ReadByProbe(this.probe)
    );
  }

  ngOnChanges() {
    if (!this.visible) {
      this.probe = null;
      this.probeHost = null;
    }
  }

}

