import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { TableMonitoringService } from "../monitoring.service";
import { BuildingService } from "../../service/monitoring-api.service";

@Component({
  selector: "app-room",
  templateUrl: "./room.component.html",
  styleUrls: ["./room.component.css"],
})
export class RoomComponent implements OnInit {
  public breadcrumb: any;
  mode: string;
  filteredRows: any[];
  data: any[];
  searchTerm: string = "";

  constructor(
    private route: ActivatedRoute,
    private monitoringService: TableMonitoringService,
    private router: Router,
    private monitoringApiService: BuildingService,
  ) {}

  ngOnInit() {
    this.route.data.subscribe((data) => {
      this.mode = data.mode;
      console.log(this.mode);
      
    });
    this.route.params.subscribe(params => {
      const buildingId = params['id'];
      if (buildingId) {
        this.fetchData(buildingId);
      }
    });
    this.breadcrumb = {
      mainlabel: "Room",
      linkBack: '/monitoring',
      isLinkBack: true,
      links: [
        {
          name: "Dashboard",
          isLink: false,
          link: "/dashboard/sales",
        },
        {
          name: "Room",
          isLink: false,
        },
      ],
    };
  }

  fetchData(buildingId) {
    this.monitoringService.getMonitoringRoomData().subscribe((Response) => {
      console.log(Response);
      
      // this.data = Response;
      // this.filteredRows = Response;
    });
    this.monitoringApiService.getRoomByBuildingId(buildingId).subscribe((res) => {
      const roomEntities = res.resp.map(entry => entry.roomEntity);
      this.data = roomEntities;
      this.filteredRows = roomEntities;
      console.log(roomEntities, 'roomEntities');
      
    });
  }

  filterRows() {
    if (!this.searchTerm) {
      this.filteredRows = [...this.data];
    } else {
      this.filteredRows = this.data.filter((row) =>
        this.rowContainsSearchTerm(row)
      );
    }
  }

  rowContainsSearchTerm(row: any): boolean {
    const searchTermLC = this.searchTerm.toLowerCase();
    return Object.values(row).some(
      (value) =>
        value !== null && value.toString().toLowerCase().includes(searchTermLC)
    );
  }
  viewRow(row) {
    this.router.navigate(["/monitoring/view-detail-room", row.id]);
  }

  editRow(row) {
    this.router.navigate(["/monitoring/edit-new-room", row.id]);
  }
}
