import {
  Component,
  OnInit,
  Input,
  AfterContentInit,
  Output,
  EventEmitter,
  OnDestroy
} from '@angular/core';
import { Store, select, StateObservable } from '@ngrx/store';
import { Observable, of } from 'rxjs';
import { catchError, exhaustMap, map, tap, take } from 'rxjs/operators';

import { RPCClientError } from '@loafer/ng-rpc';
import { MetaCrawler } from '@overflow/commons-typescript/model/meta';

import { MetaCrawlerService } from '@overflow/meta/service/meta-crawler.service';

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

  @Output() change = new EventEmitter<MetaCrawler[]>();
  @Input() disabled: boolean;

  metaCrawlers: MetaCrawler[];
  pending$: Observable<boolean>;
  error$: Observable<any>;

  constructor(
    protected store: Store<any>,
    protected metaCrawlerService: MetaCrawlerService,
  ) {
    this.includeServices = [];
  }

  ngOnInit() {
    this.metaCrawlerService.readAll()
      .pipe(
        tap(() => {
          this.pending$ = of(true);
        }),
        map((metaCrawlers: MetaCrawler[]) => {
          this.metaCrawlers = metaCrawlers;
        }),
        catchError(error => {
          this.error$ = of(error);
          return of(null);
        }),
        tap(() => {
          this.pending$ = of(false);
          this.includeServices = this.metaCrawlers.slice();
          this.change.emit(this.includeServices);
        }),
        take(1),
    ).subscribe();
  }

  ngOnDestroy() {

  }

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

  onSelectAll() {
    this.includeServices = [];
    this.metaCrawlers.forEach((value) => {
      this.includeServices.push(value);
    });
    this.change.emit(this.includeServices);
  }

  onUnselectAll() {
    this.includeServices = [];
    this.change.emit(this.includeServices);
  }

  onSelect(crawler: MetaCrawler) {
    this.change.emit(this.includeServices);
  }
  onUnselect(crawler: MetaCrawler) {
    this.change.emit(this.includeServices);
  }

}
