import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

@Component({
    selector: 'app-search-card',
    templateUrl: './search-card.component.html',
    styleUrl: './search-card.component.css',
    standalone: false
})
export class SearchCardComponent {
  @Input() public txtSearch: string;
  @Input() public disabled: boolean;
  @Input() public dataSource: MatTableDataSource<any>;
  @Input() public label: string;
  @Input() public placeholder: string;
  @Input() public btnRemoveFilter: string;

  @Output() dataValue: EventEmitter<MatTableDataSource<any>> = new EventEmitter();

  constructor() {
    this.txtSearch = '';
    this.disabled = false;
    this.dataSource = new MatTableDataSource<any>();
    this.label = 'Buscador';
    this.placeholder = 'Ingrese la palabra a buscar';
    this.btnRemoveFilter = 'Eliminar filtro';
  }

  // Método de filtrado de datos
  public applyFilter(type: string, event?: any) {
    if (!this.disabled) {
      let filterValue:string;
      if (type == 'INP') {
        filterValue = (event.target as HTMLInputElement).value;
      }else{
        this.txtSearch = event;
        filterValue = event;
      }

      if (filterValue == undefined) {
        this.txtSearch = '';
        filterValue = '';
      }

      this.dataSource.filter = filterValue.trim().toLowerCase();
      if (this.dataSource.paginator) {
        this.dataSource.paginator.firstPage();
      }
    }
    this.dataValue.emit(this.dataSource);
  }
}
