import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
import { map } from 'rxjs/operators';
import { UserPreferenceService } from '@users/user-preference.service';

export interface BoundingBox {
    readonly x: number;
    readonly y: number;
    readonly width: number;
    readonly height: number;
}

interface CellPerRow {
    readonly boundingBox: BoundingBox;
    readonly value: string;
}

export interface Table {
    readonly boundingBox: BoundingBox;
    readonly cellsPerRow: CellPerRow[][];
    readonly experimental: boolean;
    readonly csvAsBytes: string;
}

interface Response {
    readonly tables: Table[];
}

@Injectable()
export class TablesService {
    readonly #http = inject(HttpClient);
    readonly #serviceName = 'table-provider';
    readonly #defaultUrl = 'tables';
    readonly #userPreferencesService = inject(UserPreferenceService);

    get(dossierId: string, fileId: string, pageNumber: number) {
        const url = `/${this.#serviceName}/${encodeURI(this.#defaultUrl)}/${dossierId}/${fileId}`;
        const body = { pageNumber, tableExtractionType: this.#userPreferencesService.getTableExtractionType() };
        const request$ = this.#http.post<Response>(url, body);
        return firstValueFrom(request$.pipe(map(response => response.tables)));
    }
}
