import { Component, OnInit, Input, OnChanges, Output, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { MetaCrawler } from '@overflow/commons-typescript/model/meta';

import { Store, select } from '@ngrx/store';
import { RPCClientError } from '@loafer/ng-rpc/protocol';
import * as ListStore from 'packages/meta/crawler-input-item/store/list';
import { ReadCrawlerInputItemSelector } from 'packages/meta/crawler-input-item/store';
import { MetaCrawlerInputItem } from '@overflow/commons-typescript/model/meta';


@Component({
  selector: 'of-crawler-auth',
  templateUrl: './crawler-auth.component.html',
})
export class CrawlerAuthComponent implements OnInit, OnChanges {

  inputItems$ = this.listStore.pipe(select(ReadCrawlerInputItemSelector.select('inputs')));
  inputItems: MetaCrawlerInputItem[];
  title: string;

  @Output() credentialPassed = new EventEmitter<boolean>();
  @Input() crawler: MetaCrawler;

  constructor(
    private router: Router,
    private listStore: Store<ListStore.State>,
  ) { }

  ngOnInit() {
    // this.inputItems$.subscribe(
    //   (list: MetaCrawlerInputItem[]) => {
    //     if (list !== null) {
    //       if (this.inputItems !== list) {
    //         this.testPassEvent.emit(false);
    //       }
    //       this.inputItems = list;
    //     }
    //   },
    //   (error: RPCClientError) => {
    //     console.log(error.response.message);
    //   }
    // );
  }

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

    this.inputItems = [];
    // Temporary data
    if (null == this.crawler) {
      return;
    }
    this.title += ' for ' + this.crawler.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);
    }

  }

  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);
  }
}
