import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetWarehouse, ResponseDataGetWarehouse } from '../../../interfaces/inventory-management/warehouse-management.interface';
import { FormControl, Validators } from '@angular/forms';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService } from '../../../services/resources.service';
import { InventoryManagementService } from '../../../services/inventory-management/inventory-management.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-value-stock',
    templateUrl: './value-stock.component.html',
    styleUrl: './value-stock.component.css',
    standalone: false
})
export class ValueStockComponent implements OnInit, AfterViewInit {
  public isLoading: boolean;
  public dataSource: MatTableDataSource<any>;
  public displayedColumns: string[];
  public arrWarehouse: GetWarehouse[];
  public formControl: FormControl;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor (
    public resourcesService: ResourcesService,
    public _inventoryManagementService: InventoryManagementService,
  ) {
    this.isLoading = false;
    this.dataSource = new MatTableDataSource<any>();
    this.displayedColumns = [
      'ID_VALOR',
      'PERIODO',
      'VALOR',
    ];
    this.arrWarehouse = [];
    this.formControl = new FormControl(null, Validators.required);
  }
  
  async ngOnInit() {
    this.isLoading = true;
    await this._getWarehouseActives();
    await this.getValueStockByPeriod();
    this.isLoading = false;
  }

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

  private async _getWarehouseActives() {
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getWarehouseActives(USER, LINE)).then(
      async (responseData: ResponseDataGetWarehouse) => {
        if (!responseData.error) {
          this.arrWarehouse = responseData.response;
          if (this.arrWarehouse.length === 0) {
            this.resourcesService.openSnackBar(`No existen almacenes.`);
            this.resourcesService.goBack();
          }
          if (this.formControl.value === null || this.formControl.value === undefined || this.formControl.value === '') {
            this.formControl.setValue(this.arrWarehouse[0].CODIGO_ALMACEN);
          } 
        } else {
          this.resourcesService.openSnackBar(`${ responseData.msg }`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse);
        if (response !== null && response.reload) {
          await this._getWarehouseActives();
        }
      }
    );
  }

  public async getValueStockByPeriod () {
    this.isLoading = true;
    const ID_WAREHOUSE = this.formControl.value;
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getValueStockByPeriod(ID_WAREHOUSE, USER, LINE)).then(
      (responseData: any) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${ responseData.msg }`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse);
        if (response !== null && response.reload) {
          await this.getValueStockByPeriod();
        }
      } 
    );
    this.isLoading = false;  
  }
}
