import { Component, OnInit, AfterContentInit, Output, EventEmitter,
  Input, OnDestroy, OnChanges, SimpleChanges, ViewChild } from '@angular/core';
import { Store, select, StateObservable } from '@ngrx/store';
import { RPCClientError } from '@loafer/ng-rpc/protocol';
import {
  DiscoveryStartInfo,
  DiscoverZone,
  Zone,
  DiscoverPort,
  DiscoverService
} from '@overflow/commons-typescript/model/discovery';
import * as CIDR from 'ip-cidr';
import * as DiscoveredStore from '../../store/setting';
import { SettingSelector, DiscoverSelector } from '../../store';
import * as DiscoverStore from '../../store/discover';
import * as RegistStore from '../../store/regist';
import { Host } from '@overflow/commons-typescript/model/discovery';
import { Port } from '@overflow/commons-typescript/model/discovery';
import { Service } from '@overflow/commons-typescript/model/discovery';
import * as ProbeDetailStore from 'packages/probe/store';
import { Probe } from '@overflow/commons-typescript/model/probe';
import { TreeNode } from 'primeng/primeng';
import { ListSelector as ProbeListSelector } from 'packages/probe/store';
import * as ProbeListStore from 'packages/probe/store/list';
import { AuthSelector } from 'packages/member/store';
import { Domain } from '@overflow/commons-typescript/model/domain';
import { Subscription } from 'rxjs/Subscription';
import { ResultComponent } from './result/result.component';

@Component({
  selector: 'of-discovery-setting',
  templateUrl: './setting.component.html',
})
export class SettingComponent implements OnInit, AfterContentInit, OnDestroy, OnChanges {

  @Input() visible: boolean;
  @Input() probe: Probe;
  @Output() close = new EventEmitter();
  private requestStart = false;
  private started = false;

  private selectedProbe: Probe;
  private height: number;

  @ViewChild('resultComponent') resultComponent: ResultComponent;

  constructor(
    private discoverStore: Store<DiscoverStore.State>,
  ) {
  }

  ngOnInit() {
    this.height = window.innerHeight * 0.9;
  }

  ngAfterContentInit() {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['probe'] && this.probe) {
      this.selectedProbe = this.probe;
    }
  }

  ngOnDestroy() {
  }

  onProbeSelect(probe: Probe) {
    this.selectedProbe = probe;
  }

  onDiscoveryStart(discoverZone: DiscoverZone) {
    this.discoverStore.dispatch(new DiscoverStore.DiscoverZone(
      { probeID: this.selectedProbe.probeKey, discoverZone: discoverZone }));

    setTimeout(() => {
      this.started = true;
      this.requestStart = false;
    });
  }

  onCancel() {
    this.selectedProbe = null;
    this.started = false;
    this.close.emit();
  }

  onSave() {
    this.resultComponent.ngOnInit();
    this.resultComponent.save();
  }

}
