import { inject, Injectable } from "@angular/core";
import { OdataGridHelper } from "../_shared/utils/odata-grid-helper";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import * as util from '../_shared/utils/util';

export interface ProductDetail {
  id: number;
  meterId: number;
  meterTypeId: number;
  productId: number;
  number: string;
  hubCode: string;
  isUpstream: boolean;
  sourcePipeId: number;
  sourceZoneId: number;
  sourcePointIds: number[];
  deliveryPointIds: number[]
  plantIds: number[];
  description: string;
  effectiveDate: Date;
}

export interface RequiredData {
  hasModifyPermission: boolean;
  products: util.IdName[];
  productTypes: util.IdName[];
  meterTypes: util.IdName[];
  pipelines: util.Pipe[];
  sourceZones: util.Zone[];
  plantNames: util.IdName[];
  points: util.Point[];
}

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


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

  getRequiredData(productId: number) {
    const url = (`${this.baseUrl}/getRequiredData?productId=${productId}`)
    return this.http.get<RequiredData>(url);
  }

  getDetail(meterId: number, productId: number, effectiveDate: Date): Observable<ProductDetail> {
    const url = `${this.baseUrl}/GetDetail?MeterId=${meterId}&ProductId=${productId}&EffectiveDate=${effectiveDate}`;
    return this.http.get<ProductDetail>(url);
  }

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

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

}
