import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { ExchangeArticles, ResponseDataGetExchangeArticles } from '../../../interfaces/inventory-management/exchange-articles.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 { MoveArticleComponent } from './move-article/move-article.component';

@Component({
    selector: 'app-exchange-articles',
    templateUrl: './exchange-articles.component.html',
    styleUrl: './exchange-articles.component.css',
    standalone: false
})
export class ExchangeArticlesComponent implements OnInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public dataSource: MatTableDataSource<ExchangeArticles>;
  
  constructor (
    public resourcesService: ResourcesService,
    private _inventoryManagementService: InventoryManagementService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;

    this.dataSource = new MatTableDataSource<ExchangeArticles>();
  }
  
  async ngOnInit() {
    await this.getExchangeArticles();
  }

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

  public openDialog(exchangeArticles: ExchangeArticles) {
    this._dialog.open(MoveArticleComponent, {
      disableClose: true,
      width: '450px',
      maxWidth: '450px',
      data: exchangeArticles,
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.getExchangeArticles();
      }
    });
  }
}
