import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetDueDateStock, ResponseDataGetDueDateStock } from '../../../interfaces/inventory-management/due-date-stock.interface';
import { ResourcesService } from '../../../services/resources.service';
import { InventoryManagementService } from '../../../services/inventory-management/inventory-management.service';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { FormDueDateComponent } from './form-due-date/form-due-date.component';

@Component({
    selector: 'app-due-date-stock',
    templateUrl: './due-date-stock.component.html',
    styleUrl: './due-date-stock.component.css',
    standalone: false
})
export class DueDateStockComponent implements OnInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public txtSearch: string;
  public dataSource: MatTableDataSource<GetDueDateStock>;
  public arrDueDateStock: GetDueDateStock[];

  constructor(
    public resourcesService: ResourcesService,
    private _inventoryManagementService: InventoryManagementService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.txtSearch = '';
    this.dataSource = new MatTableDataSource<GetDueDateStock>();
    this.arrDueDateStock = [];
  }
  
  async ngOnInit() {
    await this.getDueDate();
  }

  public async getDueDate() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getDueDateStock(user, line)).then(
      (responseData: ResponseDataGetDueDateStock) => {
        if (!responseData.error) {

          responseData.response = responseData.response.map((dueDateStock: GetDueDateStock) => {            
            dueDateStock.FECHA_VENCIMIENTO = dueDateStock.FECHA_VENCIMIENTO === 'Ninguno' ? dueDateStock.FECHA_VENCIMIENTO : this.resourcesService.formatOnlyDate(dueDateStock.FECHA_VENCIMIENTO)
            return dueDateStock;
          });

          this.dataSource.data = responseData.response;
          this.arrDueDateStock = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getDueDate();
        }
      }
    );
    this.isLoading = false;
  }

  public applyFilter() {
    
    const dataValue: string = this.txtSearch.toString().trim().toUpperCase();
    if (dataValue.length > 0) {
      let arrDataValue: GetDueDateStock[] = [];
      this.arrDueDateStock.forEach((dueDateStock: GetDueDateStock) => {      

        let exists: boolean = false;
        
        const arrValues = Object.values(dueDateStock);
        arrValues.forEach((value: string) => {
          value = value.toString().trim().toUpperCase();
          if (value.includes(dataValue)) {
            exists = true;
          }
        });

        if (exists) {
          arrDataValue.push(dueDateStock);
        }
      });

      this.dataSource.data = arrDataValue;
    } else {
      this.dataSource.data = this.arrDueDateStock;
    }
  }

  public openDialog(dueDateStock: GetDueDateStock)  {
    this._dialog.open(FormDueDateComponent, {
      disableClose: true,
      data: dueDateStock,
      width: '420px',
      maxWidth: '420px',
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.getDueDate();
      }
    });
  }
}
