import { Injectable } from '@angular/core';
import { OdataGridHelper } from '../_shared/utils/odata-grid-helper';
import { Observable } from 'rxjs';
import dayjs from 'dayjs';
import * as util from '../_shared/utils/util';
import { map } from 'rxjs/operators';
import { State } from '@progress/kendo-data-query';
import { GridDataResult } from '@progress/kendo-angular-grid';

export interface RequiredData {
  hasApprovalPermission: boolean;
  hasDistributePermission: boolean;
}

export interface InvoiceSelection {
  id: number;
}

export interface BcStatusResponse {
  status: 'Success' | 'Error';
  message: string;
  ranAt: Date;
}

@Injectable({
  providedIn: 'root'
})
export class InvoiceGasService extends OdataGridHelper {
  private baseUrl = `${window.location.origin}/api/InvoiceNatGas`;

  constructor() {
    super()
  }

  getRequiredData(): Observable<RequiredData> {
    const url = `${this.baseUrl}/GetRequiredData`;
    return this.http.get<RequiredData>(url);
  }

  getInvoices(state: State, monthStart: Date, monthEnd: Date): Observable<GridDataResult> {
    const monthStartStr = dayjs(monthStart).format("YYYY-MM-DD");
    const monthEndStr = dayjs(monthEnd).format("YYYY-MM-DD");
    const extraParamsQueryStr = `&monthStart=${monthStartStr}&monthEnd=${monthEndStr}`;
    return this.fetch(`GetInvoiceGasGridItems`, state, extraParamsQueryStr, false);
  }

  approveInvoiceLines(invoicesToApprove: number[]): Observable<string> {
    const url = `${this.baseUrl}/ApproveInvoiceLines`;
    return this.http.put<string>(url, invoicesToApprove);
  }

  exportInvoicesXls(monthStart: Date, monthEnd: Date, state: State, fileNameOriginal: string) {
    const monthStartStr = dayjs(monthStart).format("YYYY-MM-DD");
    const monthEndStr = dayjs(monthEnd).format("YYYY-MM-DD");
    const isExportStr = true;
    const extraParamsQueryStr = `&monthStart=${monthStartStr}&monthEnd=${monthEndStr}&isExport=${isExportStr}`;
    return this.fetchExport(`GetInvoiceGasGridItems`, state, extraParamsQueryStr, fileNameOriginal);
  }

  downloadInvoice(invoiceNum: string, fileNameOriginal: string): Observable<{ fileBlob: Blob, fileName: string }> {
    const url = `${this.baseUrl}/DownloadInvoice?invoiceNum=${invoiceNum}`;
    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 };
      })
    );
  }

  mergeFiles(invoiceSelections: InvoiceSelection[]): Observable<{ fileBlob: Blob; fileName: string }> {
    const url = `${this.baseUrl}/MergeFiles`;
    return util.downloadFileWithBody(this.http, url, invoiceSelections);
  }

  exportToBc(month: Date): Observable<string> {
    const monthStr = dayjs(month).format("YYYY-MM-DD");
    const url = `${this.baseUrl}/ExportToBusinessDynamics?month=${monthStr}`;
    return this.http.get(url, { observe: 'response', responseType: 'text' }).pipe(
      map(result => {
        return result.body;
      })
    );
  }

  getLatestStatus(month: Date): Observable<BcStatusResponse> {
    const monthStr = dayjs(month).format("YYYY-MM-DD");
    const url = `${this.baseUrl}/GetLatestStatus?month=${monthStr}`;
    return this.http.get<BcStatusResponse>(url);
  }
}
