import {
  Component, OnInit, Input, AfterContentInit, Output,
  EventEmitter, OnDestroy, ViewChild
} from '@angular/core';
import { Store, select, StateObservable } from '@ngrx/store';
import { RPCClientError } from '@loafer/ng-rpc/protocol';
import * as ListStore from 'packages/probe/store/list';
import { ListSelector } from 'packages/probe/store';
import { Subscription } from 'rxjs/Subscription';
import { Probe } from '@overflow/commons-typescript/model/probe';
import { AuthSelector } from 'packages/member/store';
import { Domain } from '@overflow/commons-typescript/model/domain';
import { Dropdown } from 'primeng/primeng';

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

  @Input() preProbe: Probe;
  probesSubscription$: Subscription;
  probes$: StateObservable;
  probes: Probe[];
  selected: Probe;

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

  constructor(
    private listStore: Store<ListStore.State>,
  ) {
    this.probes$ = listStore.pipe(select(ListSelector.select('probes')));
  }

  ngOnInit() {
    this.probesSubscription$ = this.probes$.subscribe(
      (list: Probe[]) => {
        if (list !== null) {
          this.probes = list;
        }
      },
      (error: RPCClientError) => {
        console.log(error.response.message);
      }
    );
  }

  ngAfterContentInit() {
    this.getProbes();
  }

  ngOnDestroy() {
    if (this.probesSubscription$) {
      this.probesSubscription$.unsubscribe();
    }
    this.selected = null;
    this.probes = null;
  }

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

  onProbeSelect(event) {
    this.selected = event.value;
    this.probeSelected.emit(this.selected);
  }
}
