import { Component, OnInit, Input, AfterContentInit, Output, EventEmitter, OnDestroy } from '@angular/core';
import { Store, select, StateObservable } from '@ngrx/store';
import { RPCClientError } from '@loafer/ng-rpc/protocol';
import * as ListStore from 'packages/meta/crawler/store/list';
import { ReadAllCrawlerSelector } from 'packages/meta/crawler/store';
import { MetaCrawler } from '@overflow/commons-typescript/model/meta';
import { Subscription } from 'rxjs/Subscription';

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

  crawlersSubscription$: Subscription;
  crawlers$: StateObservable;
  crawlers: MetaCrawler[];
  @Output() crawlerSelected = new EventEmitter<MetaCrawler>();
  @Input() includeServices;

  @Input() disabled: boolean;

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

  ngOnInit() {
    this.crawlersSubscription$ = this.crawlers$.subscribe(
      (list: MetaCrawler[]) => {
        if (list !== null) {
          this.crawlers = [];
          this.crawlers = list;
        }
      },
      (error: RPCClientError) => {
        console.log(error);
      }
    );
  }

  ngAfterContentInit() {
    this.listStore.dispatch(new ListStore.ReadAll());
  }

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