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

export interface Item {
  SalesTaxExemptionId: number;
  Company: string;
  State: string;
  EffectiveDate: Date;
  ExpirationDate: Date;
}

export interface Detail {
  salesTaxExemptionId: number;
  companyId: number;
  stateId: number;
  effectiveDate: Date;
  expirationDate: Date;
  certificates: util.DocItem[];
  notes: string;
}

export enum SaveType {
  New = 1,
  Normal = 2
}

export interface RequiredData {
  hasModifyPermission: boolean;
  companies: util.Entity[];
  states: util.IdName[];
}

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

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

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

  getDetail(id: number): Observable<Detail> {
    const url = `${this.baseUrl}/GetDetail?id=${id}`;
    return this.http.get<Detail>(url);
  }

  saveDetail(detail: Detail, saveType: SaveType): Observable<number> {
    const url = `${this.baseUrl}/SaveDetail?saveType=${saveType}`;
    detail = convertDatesToDateOnlyStrings(detail, ['effectiveDate', 'expirationDate']);
    return this.http.put<number>(url, detail);
  }

  deleteDetail(id: number) {
    const url = `${this.baseUrl}/DeleteDetail/${id}`;
    return this.http.delete(url);
  }

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

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

}
