import { Component, Input, OnInit, OnChanges, SimpleChanges, 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 { AuthSelector } from '@overflow/shared/auth/store';

import { Sensor } from '@overflow/commons-typescript/model/sensor';
import { Page, PageParams } from '@overflow/commons-typescript/core/model';
import { Target } from '@overflow/commons-typescript/model/target';
import { DomainMember } from '@overflow/commons-typescript/model/domain';
import { SensorService } from '../service/sensor.service';

@Component({
  selector: 'of-sensor-list',
  templateUrl: './sensor-list.component.html',
})
export class SensorListComponent implements OnInit, OnChanges {
  @Input() pageNo: number;
  @Output() select = new EventEmitter<Sensor>();
  @Output() addSensor = new EventEmitter();

  page: Page<Sensor>;
  pending$: Observable<boolean>;
  error$: Observable<any>;

  totalLength: number;
  targetSensors: Object;

  constructor(
    private store: Store<any>,
    private sensorService: SensorService,
  ) {

  }

  ngOnInit() {
    this.store.pipe(
      tap(() => {
        this.pending$ = of(true);
      }),
      select(AuthSelector.selectDomainMember),
      exhaustMap((domainMember: DomainMember) => {
        const pageParams: PageParams = {
          pageNo: this.pageNo - 1,
          countPerPage: 10,
          sortCol: 'id',
          sortDirection: 'descending',
        };

        return this.sensorService.readAllByDomainID(domainMember.domain.id, pageParams)
          .pipe(
            map((page: Page<Sensor>) => {
              this.page = page;
              this.generateSensorMap();
            }),
            catchError(error => {
              this.error$ = of(error);
              return of();
            })
          );
      }
      ),
      tap(() => {
        this.pending$ = of(false);
      }),
      take(1),
    ).subscribe();

  }

  ngOnChanges(changes: SimpleChanges): void {
    this.generateSensorMap();
  }

  generateSensorMap() {
    if (!this.page) {
      return;
    }
    const tempList = [];
    for (const sensor of this.page.content) {
      const targetNode = this.existTarget(sensor, tempList);
      if (targetNode === null) {
        const sensorsNode = [];
        sensorsNode.push(sensor);
        const node = {
          target: sensor.target,
          sensors: sensorsNode,
        };

        tempList.push(node);
      } else {
        targetNode.sensors.push(sensor);
      }
    }
    this.totalLength = tempList.length;
    this.targetSensors = tempList;
  }

  existTarget(sensor: Sensor, tempList) {
    let targetNode = null;
    for (const node of tempList) {
      if (node.target.id === sensor.target.id) {
        targetNode = node;
      }
    }
    return targetNode;
  }


  // generateTargetFilter() {
  //   if (this.targetOptions) {
  //     return;
  //   }
  //   const tempList = [];
  //   for (const data of this.targetSensor) {
  //     tempList.push({ label: data.target.displayName, value: data.target.id });
  //   }
  //   this.targetOptions = tempList;
  // }

  // onAddSensor() {
  //   this.target = null;
  //   this.sensorSettingDisplay = true;
  // }

  // onAddSensorWithTarget(target: Target) {
  //   this.target = target;
  //   this.sensorSettingDisplay = true;
  // }

  // onSensorSettingClose() {
  //   this.sensorSettingDisplay = false;
  // }
  // onSensorClick(sensor) {
  //   this.router.navigate(['sensor', sensor.id, 'info']);
  // }

  // onSearch() {
  //   console.log(this.filteredName);
  //   console.log(this.selectedTargets);
  //   console.log(this.selectedStatus);
  //   alert('서버-검색 기능 구현 필요');
  // }

}

