import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { BlockUI, NgBlockUI } from 'ng-block-ui';
import { TableApiService } from 'src/app/_services/table-api.service';

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

  @BlockUI("zeroConfiguration") blockUIZeroConfiguration: NgBlockUI;

  constructor(
    private tableApiservice: TableApiService,
    private modalService: NgbModal,
    private router: Router
  ) {}

  ngOnInit() {
    this.breadcrumb = {
      mainlabel: "Master Category",
      links: [
        {
          name: "Home",
          isLink: false,
        },
        {
          name: "Master Category",
          isLink: false,
        },
      ],
    };
    this.fetchData();
  }

  fetchData() {
    this.tableApiservice.getTableInitialisationData().subscribe((response) => {
      this.data = response;
      this.filteredRows = this.data.rows;
    });
  }

  filterRows() {
    if (!this.searchTerm) {
      this.filteredRows = [...this.data.rows];
    } else {
      this.filteredRows = this.data.rows.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) {
    console.log("View row:", row);
    this.router.navigate(["/device/view", row.name]);
  }

  editRow(row) {
    console.log("Edit row:", row);
    this.router.navigate(["/device/edit", row.name]);
  }

  deleteRow(row) {
    console.log("Delete row:", row);
  }

  onTouchStart(event: Event) {
    event.preventDefault(); // Add this if necessary
  }
}
