import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, Observable } from 'rxjs';
import dayjs from 'dayjs';

export interface SosSnapshot {
  nomDate: Date;
  pipeName: string;
  pointName: string;
  fileNameOriginal: string;
  fileNameOnDisk: string;
  createdBy: Date;
  createdTime: Date;
  notes: string;
}
export interface NameInfo {
  pipeName: string;
}
export interface HistoryResponse {
  nameInfo: NameInfo;
  snapshots: SosSnapshot[];
}

@Injectable({
  providedIn: 'root'
})
export class SosSnapshotHistoryService {
  private baseUrl = `${window.location.origin}/api/SosCrude`;
  http = inject(HttpClient);


  getSnapshotHistory(pipeId: number, nomDate: Date): Observable<HistoryResponse> {
    const nomDateStr = dayjs(nomDate).format("YYYY-MM-DD");
    const url = `${this.baseUrl}/GetSnapshotHistory?pipeId=${pipeId}&nomDate=${nomDateStr}`;
    return this.http.get<HistoryResponse>(url);
  }

  downloadSnapshot(fileNameOnDisk: string, fileNameOriginal: string) {
    const url = `${this.baseUrl}/DownloadSnapshot?fileNameOnDisk=${fileNameOnDisk}`;
    return this.http.get(url, { observe: 'response', responseType: 'blob' }).pipe(
      map(result => {
        const fileBlob = result.body;
        const fileName: string = result.body.type === "text/plain" ? "Error.txt" : fileNameOriginal;
        return { fileBlob, fileName };
      })
    );
  }
}
