import { HttpClient } from "@angular/common/http";
import { inject, Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { OdataGridHelper } from "../_shared/utils/odata-grid-helper";
import { State } from "@progress/kendo-data-query";
import { GridDataResult } from "@progress/kendo-angular-grid";

// For OData grid
export interface TemplateListItem {
    Id: number;
    Name: string;
    Directory: string;
    FileName: string;
}

// For API
export interface TemplateDetail {
    id: number;
    name: string;
    directory: string;
    fileName: string;
}

export interface RequiredData {
    hasModifyPermission: boolean;
}

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

    requiredData$ = this.http.get<RequiredData>(`${this.baseUrl}/getRequiredData`)

    getItems(state: State): Observable<GridDataResult> {
        return this.fetch(`GetTemplateItems`, state, null, false);
    }

    getDetail(id: number): Observable<TemplateDetail> {
        return this.http.get<TemplateDetail>(`${this.baseUrl}/GetDetail/${id}`);
    }

    downloadTemplate(id: number): void {
        const url = `${this.baseUrl}/DownloadTemplate/${id}`;
        window.open(url, '_blank');
    }

    getUploadUrl(id: number): string {
        return `${this.baseUrl}/UploadTemplate/${id}`;
    }

    exportItems(state: State, fileNameOriginal: string) {
        return this.fetchExport(`GetTemplateItems`, state, null, fileNameOriginal);
    }
}
