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 { MetaCrawler, MetaTargetServiceType, MetaInfraTypeEnum, toMetaInfraTypeEnum, toMetaInfraType, MetaTargetType } from '@overflow/commons-typescript/model/meta';
import { MetaCrawlerService } from '../service/meta-crawler.service';
import { MetaTargetTypeService } from '../service/meta-target-type.service';


@Component({
  selector: 'of-meta-service-type-selector',
  templateUrl: './meta-service-type-selector.component.html',
})
export class MetaServiceTypeSelectorComponent implements OnInit {

  includeServices: MetaTargetType[];

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

  metaTargetTypes: MetaTargetType[];
  pending$: Observable<boolean>;
  error$: Observable<any>;

  constructor(
    private metaTargetTypeService: MetaTargetTypeService,
  ) { }

  ngOnInit() {
    this.metaTargetTypeService.readAllByMetaInfraTypeKey("SERVICE")
      .pipe(
        tap(() => {
          this.pending$ = of(true);
        }),
        map((metaTargetTypes: MetaTargetType[]) => {
          console.log(metaTargetTypes);
          this.metaTargetTypes = metaTargetTypes;
        }),
        catchError(error => {
          this.error$ = of(error);
          return of(null);
        }),
        tap(() => {
          this.pending$ = of(false);
          this.includeServices = this.metaTargetTypes.slice();
          this.change.emit(this.includeServices);
        }),
        take(1),
    ).subscribe();
  }


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

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

  onSelect(service: MetaTargetType) {
    this.change.emit(this.includeServices);
  }
  onUnselect(service: MetaTargetType) {
    this.change.emit(this.includeServices);
  }

}
