import { HttpErrorResponse } from '@angular/common/http';
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom } from 'rxjs';
import { ExchangeArticles, ResponseDataGetExchangeArticles } from 'src/app/interfaces/inventory-management/exchange-articles.interface';
import { ExchangeArticlesService } from 'src/app/services/inventory-management/exchange-articles.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { MoveArticleComponent } from './move-article/move-article.component';

@Component({
  selector: 'app-exchange-articles',
  templateUrl: './exchange-articles.component.html',
  styleUrls: ['./exchange-articles.component.css']
})
export class ExchangeArticlesComponent implements OnInit, AfterViewInit{

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public dataSource: MatTableDataSource<ExchangeArticles>;
  public displayedColumns: Array<string>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor (
    public resourcesService: ResourcesService,
    private _exchangeArticlesService: ExchangeArticlesService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;

    this.dataSource = new MatTableDataSource<ExchangeArticles>();
    this.displayedColumns = [
      'IMAGENES',
      'CODIGO',
      'ID_STOCK',
      'NOMBRE_FAMILIA',
      'NOMBRE_SUBFAMILIA',
      'ARTITULO',
      'MODELO',
      'CODIGO_MODELO',
      'ACCIONES'
    ];

  }
  
  async ngOnInit() {
    await this.getExchangeArticles();
  }

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

  public async getExchangeArticles() {
    this.isLoading = true;
    await lastValueFrom(this._exchangeArticlesService.getCurrentLocationArtitles()).then(
      (responseData: ResponseDataGetExchangeArticles) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoading = false;
  }

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