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 { IdName, SaveType, convertDatesToDateOnlyStrings } from '../_shared/utils/util';

export interface Item {
  Id: number;
  Name: string;
  ProductionMonth: Date;
  StatementDate: Date;
  Plant: string;
  PlantId: number;
  Producer: string;
  ProducerId: number;
  EthanePrice: number;
  PropanePrice: number;
  IsoButanePrice: number;
  NormalButanePrice: number;
  NaturalGasolinePrice: number;
  ScrubberPrice: number;
}

export interface Detail {
  id: number;
  name: string;
  productionMonth: Date;
  statementDate: Date;
  plantId: number;
  producerId: number;
  ethanePrice: number;
  propanePrice: number;
  isoButanePrice: number;
  normalButanePrice: number;
  naturalGasolinePrice: number;
  scrubberPrice: number;
}

export interface RequiredData {
  hasModifyPermission: boolean;
  plants: IdName[];
  producers: IdName[];
  pricesNames: IdName[];
  payoutTypes: { Id: number; Name: string; Description: string }[];
  meters: { MeterId: number; MeterName: string; PlantIds: number[]; ProducerIds: number[] }[];
  statementDescriptors: IdName[];
}

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

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

  getItems(state: State): Observable<GridDataResult> {
    return this.fetch(`GetPlantStatementPricesItems`, 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, ['productionMonth', 'statementDate']);
    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(`GetPlantStatementPricesItems`, state, null, fileNameOriginal);
  }

}
