import { Component, OnInit, AfterViewInit, ViewChild, AfterContentInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Sensor } from '@overflow/commons-typescript/model/sensor';
import { Store, select } from '@ngrx/store';
import * as SensorStore from '../../store';
import { RPCClientError } from '@loafer/ng-rpc/protocol';
import * as ListStore from '../../store/list';
import { sensorListSelector } from '../../store';
import { Domain } from '@overflow/commons-typescript/model/domain';
import { AuthSelector } from 'packages/member/store';
import { Page, PageParams } from 'app/commons/model';
import { Target } from '@overflow/commons-typescript/model/target';
import { SettingComponent } from '../setting/setting.component';
import { SelectItem } from 'primeng/primeng';

import { Infra } from '@overflow/commons-typescript/model/infra';
import * as InfraDetailStore from 'packages/infra/store/detail';
import { DetailSelector as InfraDetailSelector } from 'packages/infra/store';
import { Subscription } from 'rxjs/Subscription';


@Component({
  selector: 'of-sensor-list',
  templateUrl: './list.component.html',
})
export class ListComponent implements OnInit, AfterContentInit, OnDestroy {

  sensorsSubscription$: Subscription;
  sensorList$;
  PAGE_SIZE = '99999';
  totalLength = 0;
  sensorSettingDisplay = false;

  sensors: Sensor[];
  target: Target = null;
  targetSensor;

  // filter
  targetOptions: SelectItem[];
  filteredName: string;
  selectedTargets: string[] = [];
  selectedStatus: string[] = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private store: Store<ListStore.State>,
  ) {
    this.sensorList$ = this.store.pipe(select(sensorListSelector.select('page')));
  }

  ngOnInit() {
    // this.sensorsSubscription$ = this.sensorList$.subscribe(
    //   (page: Page) => {
    //     if (page != null) {
    //       this.sensors = page.content;
    //       this.generateSensorMap();
    //     }
    //   },
    //   (error: RPCClientError) => {
    //     console.log(error.response.message);
    //   }
    // );
  }

  ngAfterContentInit() {
    this.getSensors(0);
  }

  ngOnDestroy() {
    if (this.sensorsSubscription$) {
      this.sensorsSubscription$.unsubscribe();
    }
  }


  getSensors(pageIndex: number) {
    this.store.select(AuthSelector.select('domain')).subscribe(
      (domain: Domain) => {
        const pageParams: PageParams = {
          pageNo: pageIndex + '',
          countPerPage: this.PAGE_SIZE,
          sortCol: 'id',
          sortDirection: 'descending'
        };
        this.store.dispatch(new ListStore.ReadAllByDomain({ domain, pageParams }));
      },
      (error) => {
        console.log(error);
      }
    );
  }

  generateSensorMap() {
    const tempList = [];
    for (const sensor of this.sensors) {
      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.targetSensor = tempList;

    this.generateTargetFilter();
  }


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

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

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

}

