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 } from '../_shared/utils/util';

export interface Detail {
  id: number;
  month: Date;
  counterpartyId: number;
  contractId: number;
  asOfDate: Date;
  detailMeters: DetailMeter[];
}

export interface Item {
  Id: number;
  Month: Date;
  CounterpartyName: string;
  ContractNum: string;
  AsOfDate: Date;
}

export interface DetailMeter {
  meterId: number;
  titleMeterId: number;
  qb1: number;
  qb2: number;
  qb3: number;
  qb4: number;
}

export interface ContractItem {
  contractId: number;
  contractNum: string;
  counterpartyId: number;
}

export interface MeterItem {
  meterId: number;
  meterName: string;
}

export interface CounterpartyItem {
  counterpartyId: number;
  counterpartyName: string;
}

export interface RequiredData {
  hasModifyPermission: boolean;
  contracts: ContractItem[];
  meters: MeterItem[];
  counterparties: CounterpartyItem[];

}

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

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

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

  getItems(state: State, showOriginal: boolean): Observable<GridDataResult> {
    const url = `GetQualityBankItems?showOriginal=${showOriginal}`;
    return this.fetch(url, state, null, false);
  }

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

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

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

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