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

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


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

  crawlers$ = this.listStore.pipe(select(ReadAllCrawlerSelector.select('metaCrawlerList')));
  @Input() target: Target;
  crawlers: MetaCrawler[];
  @Output() crawlerSelected = new EventEmitter<MetaCrawler>();

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

  ngOnInit() {
    // this.crawlers$.subscribe(
    //   (list: MetaCrawler[]) => {
    //     if (list !== null) {
    //       this.crawlers = list;
    //     }
    //   },
    //   (error: RPCClientError) => {
    //     console.log(error.response.message);
    //   }
    // );

  }

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

  ngOnChanges() {

    this.crawlers = [];
    if (null == this.target) {
      return;
    }

    // Temporary Data
    for (let i = 0; i < 4; i++) {
      const c: MetaCrawler = {
        id: i,
        name: 'CrawlerName' + i + ' For ' + this.target.displayName,
      };
      this.crawlers.push(c);
    }

  }

  onSelectionChange(event) {
    // FIXME: 이미 해당 크롤러를 사용하는 센서가 있는지 확인해야 함
    // 있다면, 사용자에 알려주고 수정 모드로 변경
    // 기존 SensorDisplayItem 목록 조회
    this.crawlerSelected.emit(event.value[0]);
  }
}
