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

import { RPCClientError } from '@loafer/ng-rpc';

import { Target } from '@overflow/commons-typescript/model/target';
import { MetaCrawler } from '@overflow/commons-typescript/model/meta';
import { MetaCrawlerService } from '../service/meta-crawler.service';


@Component({
  selector: 'of-meta-crawler',
  templateUrl: './meta-crawler.component.html',
})
export class MetaCrawlerComponent implements OnInit {
  @Input() target: Target;
  @Output() selected = new EventEmitter<MetaCrawler>();

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

  constructor(
    private metaCrawlerService: MetaCrawlerService,
  ) { }

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

}
