import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetDocumentsByStock, ResponseDataGetDocumentByStock } from '../../../../interfaces/inventory-management/document-association.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService } from '../../../../services/resources.service';
import { EncService } from '../../../../services/enc.service';
import { InventoryManagementService } from '../../../../services/inventory-management/inventory-management.service';
import { ActivatedRoute } from '@angular/router';
import { GdelService } from '../../../../services/gdel.service';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { FormDocumentComponent } from '../form-document/form-document.component';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { ResponseDataGetPublicDocumentUrl } from '../../../../interfaces/gdel.interface';

@Component({
    selector: 'app-document-by-stock',
    templateUrl: './document-by-stock.component.html',
    styleUrl: './document-by-stock.component.css',
    standalone: false
})
export class DocumentByStockComponent implements OnInit, AfterViewInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;

  public dataSource: MatTableDataSource<GetDocumentsByStock>;
  public displayedColumns: Array<string>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  public idStock!: string;

  constructor(
    public resourcesService: ResourcesService,
    private _encService: EncService,
    private _inventoryManagementService: InventoryManagementService,
    private _activatedRoute: ActivatedRoute,
    private _gdelService: GdelService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;

    this.dataSource = new MatTableDataSource<GetDocumentsByStock>();
    this.displayedColumns = [
      'DOCUMENTO',
      'EXTENSION',
      'CLASIFICACION',
      'VERSION',
      'TAMANO',
      'USUARIO_MODIFICA',
      'FECHA_MODIFICA',
      'ESTADO',
      'ACCIONES',
    ]
  }

  async ngOnInit() {
    const encStock = this._activatedRoute.snapshot.paramMap.get('idStock');
    if (encStock === null) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el número de stock.`);
      this.resourcesService.goBack();
      return;
    }
    this.idStock = await this._encService.decrypt(encStock);
    await this.getDocumentsByStock();
  }

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

  public async getDocumentsByStock() {
    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.getDocumentsByStock(encStock, user, line)).then(
      (responseData: ResponseDataGetDocumentByStock) => {
        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.getDocumentsByStock();
        }
      }
    );
    this.isLoading = false;
  }

  public async goForm(typeForm: 'REG' | 'UPD', documentsByStock?: GetDocumentsByStock) {
    this._dialog.open(FormDocumentComponent, {
      disableClose: true,
      data: this.idStock,
      width: '450px',
      maxWidth: '450px',
    }).afterClosed().subscribe(async (result) => {
      if (result) {
        await this.getDocumentsByStock();
      }
    });
  }

  public alert(typeAlert: 'DOW', documentsByStock: any) {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de descargar el documento ${documentsByStock.DOCUMENTO}.${documentsByStock.EXTENSION}?`,
        icon: `warning`,
      }
    }).afterClosed().subscribe(async (result) => {
      if (result)  {
        await this.downloadDocument(documentsByStock)
      }
    });
  }

  public async downloadDocument(documentsByStock: any) {
    const codeDocument:string = documentsByStock.ID;
    const idUser:string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._gdelService.getPublicDocumentUrl(codeDocument, idUser, line)).then(
      (responseData: ResponseDataGetPublicDocumentUrl) => {
        if (!responseData.error) {
          window.open(`${responseData.response.public_uri}`, '_blank');
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.downloadDocument(documentsByStock);
        }
      }
    );
  }
}
