import { Component, Input, OnInit, OnChanges, SimpleChanges, Output, EventEmitter } from '@angular/core';
import { Sensor } from '@overflow/commons-typescript/model/sensor';
import { Page } from '@overflow/commons-typescript/model/commons/Page';
import { Target } from '@overflow/commons-typescript/model/target';

@Component({
  selector: 'of-sensor-list',
  templateUrl: './list.component.html',
})
export class SensorListComponent implements OnChanges {

  @Input() page: Page<Sensor>;
  @Output() addSensor = new EventEmitter();

  totalLength: number;
  targetSensors: Object;

  constructor(
  ) { }

  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('서버-검색 기능 구현 필요');
  // }

}

