import { Component, OnInit, Inject, AfterContentInit, OnDestroy, Input, 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 { ConfirmationService } from 'primeng/primeng';

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

import { Sensor } from '@overflow/commons-typescript/model/sensor';
import { SensorService } from '../service/sensor.service';
import { Target } from '@overflow/commons-typescript/model/target';
import { MetaCrawler } from '@overflow/commons-typescript/model/meta';

@Component({
  selector: 'of-sensor-detail',
  templateUrl: './sensor-detail.component.html',
  providers: [ConfirmationService]
})
export class SensorDetailComponent implements OnInit, OnDestroy {
  @Input() sensorID: number;
  @Output() selectTarget = new EventEmitter<Target>();

  sensor: Sensor;
  sensorSettingDisplay: boolean;

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

  metaCrawler: MetaCrawler;

  constructor(
    private confirmationService: ConfirmationService,
    private store: Store<any>,
    private sensorService: SensorService,
  ) {
    this.sensorSettingDisplay = false;
  }

  ngOnInit() {
    if (0 < this.sensorID) {
      // get sensor
      this.sensorService.read(this.sensorID)
        .pipe(
          tap(() => {
            this.pending$ = of(true);
          }),
          map((sensor: Sensor) => {
            this.sensor = sensor;
          }),
          catchError(error => {
            this.error$ = of(error);
            return of();
          }),
          tap(() => {
            this.pending$ = of(false);
          }),
          take(1),
      ).subscribe();

    } else {
      // new sensor
      this.sensor = {};
    }
  }

  ngOnDestroy() {
  }

  onStartOrStop() { }

  onEdit() {
    this.sensorSettingDisplay = true;
  }

  onRemove() {
    this.confirmationService.confirm({
      header: 'Are you sure to remove this Sensor?',
      icon: 'fa fa-trash',
      message: 'All the related data will be deleted. ',
      accept: () => {
        alert('으앙 안돼 지우지마ㅠㅠ');
      },
      reject: () => {
      }
    });
  }

  onMetaCrawlerSelected(metaCrawler: MetaCrawler) {
    this.metaCrawler = metaCrawler;
  }
}

