import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetLocationByStock, ResponseDataGetLocationByStock } from '../../../../interfaces/inventory-management/location-stock.interface';
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 { ActivatedRoute, Router } from '@angular/router';
import { EncService } from '../../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { DetailsHistoryLocationComponent } from '../details-history-location/details-history-location.component';

@Component({
    selector: 'app-history-location-stock',
    templateUrl: './history-location-stock.component.html',
    styleUrl: './history-location-stock.component.css',
    standalone: false
})
export class HistoryLocationStockComponent implements OnInit, AfterViewInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public dataSource: MatTableDataSource<GetLocationByStock>;
  public displayedColumns: Array<string>; 
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  public idStock!: string;

  constructor(
    public resourcesService: ResourcesService,
    private _inventoryManagementService: InventoryManagementService,
    private _activateRoute: ActivatedRoute,
    private _router: Router,
    private _encService: EncService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.dataSource = new MatTableDataSource<GetLocationByStock>();
    this.displayedColumns = [
      'ID_UBICACION',
      'CODIGO_EQUIPAMIENTO',
      'USUARIO_MODIFICA',
      'FECHA_MODIFICA',
      'ESTADO',
      'ACCIONES',
    ];
  }
  
  async ngOnInit() {
    this.isLoading = true;
    await this.getInfoStock();
    await this.getLocationByStock();
    this.isLoading = false;
  }
  
  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  private async getInfoStock() {
    const encStock = this._activateRoute.snapshot.paramMap.get('idStock');
    if (encStock === null) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el ID del Stock.`);
      this.resourcesService.goBack();
      return;
    }

    this.idStock = await this._encService.decrypt(encStock);
  }

  public async getLocationByStock() {
    this.isLoading = true;
    const encStock: string = await this._encService.encrypt(this.idStock);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getLocationByStock(encStock, user, line)).then(
      (responseData: ResponseDataGetLocationByStock) => {
        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.getLocationByStock();
        }
      }
    );
    this.isLoading = false;
  }

  public openDialogDetailsLocation(locationByStock: GetLocationByStock) {
    const idLocation = locationByStock.ID_UBICACION.replace('#', '');
    this._dialog.open(DetailsHistoryLocationComponent, {
      disableClose: true,
      width: '700px',
      maxWidth: '700px',
      data: {
        idStock: this.idStock,
        idLocation: idLocation,
      }
    });
  }
}
