import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetDescriptionSheetStock, ResponseDataGetDescriptionSheetStock } from '../../../interfaces/inventory-management/description-sheet-stock.interface';
import { ResourcesService } from '../../../services/resources.service';
import { InventoryManagementService } from '../../../services/inventory-management/inventory-management.service';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-description-sheet-stock',
    templateUrl: './description-sheet-stock.component.html',
    styleUrl: './description-sheet-stock.component.css',
    standalone: false
})
export class DescriptionSheetStockComponent implements OnInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public txtSearch: string;
  public dataSource: MatTableDataSource<GetDescriptionSheetStock>;
  public arrDescriptionSheetStock: GetDescriptionSheetStock[];
  
  constructor (
    public resourcesService: ResourcesService,
    private _inventoryManagementService: InventoryManagementService,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _matIconRegistry: MatIconRegistry,
    private _domSanitizer: DomSanitizer,

  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.txtSearch = '';
    this.dataSource = new MatTableDataSource<GetDescriptionSheetStock>();
    this.arrDescriptionSheetStock = [];

    this._matIconRegistry.addSvgIcon(
      'xls',
      this._domSanitizer.bypassSecurityTrustResourceUrl(window.location.origin+"/assets/img/custom_icons/xls.svg")
    )
  }

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

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

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

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

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

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

  public alert(typeAlert: 'XLS' | 'PDF', descriptionSheetStock: GetDescriptionSheetStock) {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      width: '400px',
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de descargar la ficha descriptiva en formato ${typeAlert} del número de stock #${descriptionSheetStock.ID_STOCK}?`,
        icon: `warning`,
      }
    }).afterClosed().subscribe(async (result) => {
      if ( result && typeAlert === 'XLS') {
        await this.createDescriptionSheetStockXLS(descriptionSheetStock.ID_STOCK);
      }
      if ( result && typeAlert === 'PDF') {
        await this.createDescriptionSheetStockPDF(descriptionSheetStock.ID_STOCK);
      } 
    });
  }

  private async createDescriptionSheetStockXLS(idStock: string) {
    const encStock = await this._encService.encrypt(idStock);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.createDescriptionSheetStockXLS(encStock, user, line)).then(
      (responseData: any) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.createDescriptionSheetStockXLS(idStock);
        }
      }
    );
  }
  
  private async createDescriptionSheetStockPDF(idStock: string) {
    const encStock = await this._encService.encrypt(idStock);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.createDescriptionSheetStockPDF(encStock, user, line)).then(
      (responseData: any) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.createDescriptionSheetStockPDF(idStock);
        }
      }
    );
  }
}
