import { Component, Inject, OnInit } from '@angular/core';
import { GetArtitleByInformation, ResponseDataGetArtitleByInformation } from '../../../../../interfaces/acquisition-management/artitle.interface';
import { SliderData } from '../../../../../interfaces/slider.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { AcquisitionService } from '../../../../../services/acquisition-management/acquisition.service';
import { ResourcesService } from '../../../../../services/resources.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-view-details-line',
    templateUrl: './view-details-line.component.html',
    styleUrl: './view-details-line.component.css',
    standalone: false
})
export class ViewDetailsLineComponent implements OnInit {
  public isLoading: boolean;
  public objArtitles: GetArtitleByInformation;

  public arrSlider: Array<SliderData>;

  constructor(
    @Inject(MAT_DIALOG_DATA) public idInformation: string,
    private _artitleService: AcquisitionService,
    public resourcesService: ResourcesService,
  ) {
    this.objArtitles = {} as GetArtitleByInformation;
    this.isLoading = false;
    this.arrSlider = [];
  }

  ngOnInit(): void {
    this.getArtitleByInformation();
  }

  private async getArtitleByInformation() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._artitleService.getArtitleByInformation(this.idInformation, user, line)).then(
      (responseData: ResponseDataGetArtitleByInformation) => {
        if ( !responseData.error ) {
          this.objArtitles = responseData.response;

          let arrDataSlider: Array<SliderData> = [];
          this.objArtitles.DEAR_IMAG.map((element:string) => {
            arrDataSlider.push({ image: `${element}` });
          })
          this.arrSlider = arrDataSlider;
        } else {
          this.resourcesService.openSnackBar( responseData.msg );
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getArtitleByInformation();
        }
      }
    );
    this.isLoading = false;
  }
}
