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 { MetaCrawlerInputItem } from '@overflow/commons-typescript/model/meta';
import { MetaCrawler } from '@overflow/commons-typescript/model/meta';
import { MetaCrawlerInputItemService } from '../service/meta-crawler-input-item.service';


@Component({
  selector: 'of-meta-crawler-input-item',
  templateUrl: './meta-crawler-input-item.component.html',
})
export class MetaCrawlerInputItemComponent implements OnInit, OnChanges {
  @Input() metaCrawler: MetaCrawler;
  @Output() credentialPassed = new EventEmitter<boolean>();


  pending$: Observable<boolean>;
  error$: Observable<any>;

  metaCrawlerInputItems: MetaCrawlerInputItem[];
  title: string;


  constructor(
    private store: Store<any>,
    private metaCrawlerInputItemService: MetaCrawlerInputItemService
  ) { }

  ngOnInit() {
  }

  ngOnChanges() {
    // this.getCrawlerAuthInputItems();
    this.title = '3. Credentials';

    // Temporary data
    if (null == this.metaCrawler) {
      return;
    }
    // this.title += ' for ' + this.metaCrawler.name;
    // for (let i = 0; i < 10; i++) {
    //   const item: MetaCrawlerInputItem = {
    //     id: i,
    //     // inputType: {
    //     //   id: i,
    //     //   name:  '',
    //     //   description: '',
    //     // },
    //     crawler: null,
    //     description: '',
    //     name: '',
    //     createDate: new Date(),
    //     required: true,
    //     defaultValue: '',
    //     pattern: '',
    //     keyName: '',
    //     keyValue: '',
    //   };
    //   this.inputItems.push(item);
    // }

    this.metaCrawlerInputItemService.readAllByMetaCrawlerID(this.metaCrawler.id)
      .pipe(
        tap(() => {
          this.pending$ = of(true);
        }),
        map((metaCrawlerInputItems: MetaCrawlerInputItem[]) => {
          this.metaCrawlerInputItems = metaCrawlerInputItems;
        }),
        catchError(error => {
          this.error$ = of(error);
          return of();
        }),
        tap(() => {
          this.pending$ = of(false);
        }),
        take(1),
    ).subscribe();

  }

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

  testCredentials() {
    // switch (this.crawler.id) {
    //   case 1:
    //     break;
    //   case 2:
    //     break;
    //   case 3:
    //     break;
    //   default :
    //     break;
    // }
    this.credentialPassed.emit(true);
  }
}
