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

export interface Item {
  TransferMeterId: number;
  Pipe1Name: string;
  Zone1Name: string;
  Meter1Name: string;
  Pipe2Name: string;
  Zone2Name: string;
  Meter2Name: string;
  Product: string;
}

export interface Detail {
  transferMeterId: number;
  productId: number;
  pipe1Id: number;
  pipe1Name: string;
  zone1Id: number;
  zone1Name: string;
  meter1Id: number;
  meter1Name: string;
  pipe2Id: number;
  pipe2Name: string;
  zone2Id: number;
  zone2Name: string;
  meter2Id: number;
  meter2Name: string;
}

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

export interface PipelineDetail {
  pipelineId: number;
  fullName: string;
  shortName: string;
  pipeCode: string;
  productIds: number[];
  pipelineDescription: string;
}

export interface RequiredData {
  hasModifyPermission: boolean;
  pipelines: PipelineDetail[];
  meters: MeterItem[];
  zones: ZoneItem[];
  products: util.IdName[];
}

export interface ZoneItem {
  zoneId: number;
  zoneName: string;
  pipeId: number;
}

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

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

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

  getItems(state: State): Observable<GridDataResult> {
    return this.fetch(`GetTransferMeterItems`, 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}`;
    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(`GetTransferMeterItems`, state, null, fileNameOriginal);
  }

}
