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

export interface Item {
  LeaseId: number;
  Name: string;
  Number: string;
  LeaseType: string;
  LeaseInactiveDate: Date;
}

export interface Detail {
  leaseId: number;
  name: string;
  number: number;
  leaseTypeId: number;
  inactiveDate: Date;
}

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

export interface RequiredData {
  hasModifyPermission: boolean;
  products: IdName[];
  leaseTypes: IdName[];
}

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

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

  getItems(state: State, asOfDate: Date): Observable<GridDataResult> {
    const asOfDateStr = asOfDate ? dayjs(asOfDate).format("YYYY-MM-DD") : null;
    return this.fetch(`GetLeaseItems`, state, asOfDateStr ? `&asOfDate=${asOfDateStr}` : '', 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, ['inactiveDate']);
    return this.http.put<number>(url, detail);
  }

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

  exportItems(state: State, asOfDate: Date, fileNameOriginal: string) {
    const asOfDateStr = asOfDate ? dayjs(asOfDate).format("YYYY-MM-DD") : null;
    return this.fetchExport(`GetLeaseItems`, state, asOfDateStr ? `&asOfDate=${asOfDateStr}` : '', fileNameOriginal);
  }

}

