import { Component, OnInit, AfterViewInit, AfterContentInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';

import { Store, select } from '@ngrx/store';

import { RPCClientError } from '@loafer/ng-rpc/protocol';
import { Domain } from 'packages/domain/model';
import { AuthSelector } from 'packages/member/store';

import { Probe, ProbeHost } from '../../model';
import * as ListStore from '../../store/probe-host-list';
import { ProbeHostListSelector } from '../../store';

@Component({
  selector: 'of-probe-list',
  templateUrl: './list.component.html',
})
export class ListComponent implements OnInit, AfterContentInit {
  probeHosts$ = this.store.pipe(select(ProbeHostListSelector.select('probeHosts')));
  probeHosts: ProbeHost[];

  constructor(
    private router: Router,
    private store: Store<ListStore.State>
  ) {
  }

  ngOnInit() {
    this.probeHosts$.subscribe(
      (probeHosts: ProbeHost[]) => {
        console.log(probeHosts);
        this.probeHosts = probeHosts;
      },
      (error: RPCClientError) => {
        console.log(error.response.message);
      }
    );
  }

  ngAfterContentInit() {
    this.store.select(AuthSelector.select('domain')).subscribe(
      (domain: Domain) => {
        this.store.dispatch(new ListStore.ReadAllByDomain(domain));
      },
      (error) => {
        console.log(error);
      }
    );

  }

  onRowSelect(event) {
    this.router.navigate(['probe', event.data.id, 'info']);
  }
}
