import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { DocumentFormComponent } from '../document-form/document-form.component';


const DATA_EXAMPLE: Array<any> = [
  {
    idDocumento: '000001',
    documento: 'Manual de Optiplex 5090',
    tipoDocumento: 'Referencias',
    fechaModificacion: '10/11/2022 T10:27:32',
    versionDocumento: '01',
  },
];


@Component({
  selector: 'app-document-order',
  templateUrl: './document-order.component.html',
  styleUrls: ['./document-order.component.css']
})
export class DocumentOrderComponent implements AfterViewInit, OnInit {

  public displayedColumns: Array<string> = [
    'ITEM1',
    'ITEM2',
    'ITEM3',
    'ITEM4',
    'ITEM5',
    'ITEM6',
  ];

  // ---- Loading Data ----
  public isLoading: boolean = false;
  public isLoadingForm: boolean = false;

  // ---- SmartPage ----
  public btnSmall: boolean = false;

  // ---- Tabla ----
  public dataSource: MatTableDataSource<any>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public txtBuscador:string;

  constructor(
    public dialog: MatDialog,
  ) {
    this.dataSource = new MatTableDataSource();
    this.txtBuscador = '';
  }

  ngOnInit(): void {
    this.onResize();
    this.getDocuments();
  }

  ngAfterViewInit(): void {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  public getDocuments(){
    this.dataSource.data = DATA_EXAMPLE;
  }

  public openDialog(action: string, data: any = null) {
    if (action === 'REG') {
      const dialogRef = this.dialog.open(DocumentFormComponent, {
        width: '400px',
        disableClose: true,
      });
    }

  }

  // Método de filtrado de datos
  public applyFilter(event: any, type: string):void {
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  // Método para reajustar los botones según sus dimensiones
  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

}
