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 * as util from '../_shared/utils/util'

export interface HistoryArray {
  historyItems: HistoryItem[];
}

export interface Detail {
  historyItemsToSave: HistoryArray
}

export interface HistoryItem {
  actualVolume: number;
  price: number;
  priceAdj: number;
  transportRate: number;
  isVolumeEdited: boolean;
  isPriceEdited: boolean;
  isPriceAdjEdited: boolean;
  isTransportRateEdited: boolean;
  saveDate: Date;
  supplyNomId: number;
  marketNomId: number;
  lastTransferId: number;
}

export interface RequiredData {
  hasModifyPermission: boolean;
}

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

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

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

  getHistoryItems(actualTypeId: number, supplyNomId: number, marketNomId: number, lastTransferId: number): Observable<HistoryItem[]> {
    let url = `${this.baseUrl}/GetHistoryItems?actualTypeId=${actualTypeId}&supplyNomId=${supplyNomId}&marketNomId=${marketNomId}`;
    if (lastTransferId !== null)
      url += `&lastTransferId=${lastTransferId}`;

    return this.http.get<HistoryItem[]>(url);
  }

  saveHistoryItems(actualTypeId: number, supplyNomId: number, marketNomId: number, lastTransferId: number, itemsToSave: HistoryItem[]): Observable<number> {
    itemsToSave = util.convertDatesToDateOnlyStrings(itemsToSave, ['saveDate']);
    let url = `${this.baseUrl}/SaveHistoryItems?actualTypeId=${actualTypeId}&supplyNomId=${supplyNomId}&marketNomId=${marketNomId}`;
    if (lastTransferId !== null)
      url += `&lastTransferId=${lastTransferId}`;

    return this.http.put<number>(url, itemsToSave);
  }
}
