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

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

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

import { Probe, ProbeHost } from '@overflow/commons-typescript/model/probe';
import * as ListStore from '../../store/probe-host-list';
import { ProbeHostListSelector } from '../../store';
import { Subscription } from 'rxjs/Subscription';

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

  @Output() select = new EventEmitter<Probe>();

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

  ngOnInit() {
    this.probeHostsSubscription$ = 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);
    //   }
    // );

    // temp
    const probeHost: ProbeHost = {
      id: 1,
      probe: {
        id: 1,
        displayName: 'ddd',
        cidr: 'dddd',
        authorizeDate: new Date(),
        authorizeMember: {
          name: 'ddd'
        }
      },
      host: {
        id: 1,
        ipv4: 'aaaa',
        os: {
          vendor: {
            name: 'dd'
          }
        },
      }
    };
    this.probeHosts = [];
    this.probeHosts.push(probeHost);

  }

  ngOnDestroy() {
    if (this.probeHostsSubscription$) {
      this.probeHostsSubscription$.unsubscribe();
    }
  }

  onRowSelect(event) {
    this.select.emit(event.data.probe);
  }

  getUptime(probe: Probe) {
    // if (probe.connectDate === null || probe.connectDate ==== undefined) {
    //   return 'Not Connected.';
    // }
    // const currentDate = new Date();
    return 'Uptime';
  }
}
