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 { State } from '@progress/kendo-data-query';
import { GridDataResult } from '@progress/kendo-angular-grid';
import dayjs from 'dayjs';
import * as util from '../_shared/utils/util';

export interface Item {
  MeterId: number;
  Name: string;
  InactiveDate: Date;
  ProducerIds: string;
  Lease: string;
  Location: string;
  Latitude: number;
  Longitude: number;
  State: number;
  Numbers: string;
  Pipelines: string;
  PointNames: string;
  HubCodes: string;
  MeterTypes: string;
}

export interface Detail {
  meterId: number;
  commonDetail: CommonDetail;
}

export interface CommonDetail {
  meterId: number;
  name: string;
  meterTypeId: number;
  inactiveDate: Date;
  stateId: number;
  countyId: number;
  locationId: number;
  leaseId: number;
  latitude: number;
  longitude: number;
  producerIds: number[];
  description: string;
}

export interface MeterProductItem {
  id: number;
  meterId: number;
  productId: number;
  meterType: string;
  product: string;
  number: string;
  hubCode: string;
  isUpstream: string;
  sourcePipe: string;
  sourceZone: string;
  sourcePointIds: string;
  deliveryPointIds: string
  plantIds: string;
  description: string;
}

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

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

@Injectable({
  providedIn: 'root'
})
export class MeterService extends OdataGridHelper {
  private baseUrl = `${window.location.origin}/api/Meter`;
  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(`GetMeterItems`, state, asOfDateStr ? `&asOfDate=${asOfDateStr}` : '', false);
  }

  getMeterProducts(meterId: number): Observable<MeterProductItem[]> {
    const url = `${this.baseUrl}/GetMeterProducts/${meterId}`;
    return this.http.get<MeterProductItem[]>(url);
  }

  saveDetail(detail: Detail, saveType: SaveType): Observable<number> {
    const url = `${this.baseUrl}/SaveDetail?saveType=${saveType}`;
    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(`GetMeterItems`, state, asOfDateStr ? `&asOfDate=${asOfDateStr}` : '', fileNameOriginal);
  }
}
