import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetMaxMinStock, ResponseDataGetMaxMinStock } from '../../../interfaces/inventory-management/max-min-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 { FormMaxMinStockComponent } from './form-max-min-stock/form-max-min-stock.component';

@Component({
    selector: 'app-max-min-stock',
    templateUrl: './max-min-stock.component.html',
    styleUrl: './max-min-stock.component.css',
    standalone: false
})
export class MaxMinStockComponent implements OnInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public txtSearch: string;
  public dataSource: MatTableDataSource<GetMaxMinStock>;
  public arrMaxMinStock: GetMaxMinStock[];

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

  public async getMaxMinStock() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getMaxMinStock(user, line)).then(
      (responseData: ResponseDataGetMaxMinStock) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
          this.arrMaxMinStock = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getMaxMinStock();
        }
      }
    );
    this.isLoading = false;
  }

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

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

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

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

  public openDialog(maxMinStock: GetMaxMinStock) {
    this._dialog.open(FormMaxMinStockComponent, {
      disableClose: true,
      width: '420px',
      maxWidth: '420px',
      data: maxMinStock,
    }).afterClosed().subscribe(async (result) => {
      if (result) {
        await this.getMaxMinStock();
      }
    });
  }
}
