import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { OdataGridHelper } from '../_shared/utils/odata-grid-helper';
import { map, 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 {
  Id: number;
  ContractNum: string;
  StartDate: Date;
  EndDate?: Date;
  Pipeline: string;
  ContractType: string;
  RateSchedule: string;
  Shipper: string;
  CapacityRelease: string;
  ReceiptZones: string;
  ReceiptMeters: string;
  DeliveryZones: string;
  DeliveryMeters: string;
  Product: string;
}

export interface Detail {
  id: number;
  contractNum: string;
  startDate: Date;
  endDate: Date;
  isDefaultContract: boolean;
  pipelineId: number;
  contractTypeId: number;
  rateScheduleId: number;
  shipperId: number;
  contractOwnerId: number;
  capacityIsRelease: boolean;
  capacityIsBuy: boolean;
  capacityCounterpartyId: number;
  capacityDemandCharge: number;
  capacityRateUnitId: number;
  receiptZoneIds: number[];
  receiptMeterIds: number[];
  deliveryZoneIds: number[],
  deliveryMeterIds: number[],
  isPtrContract: boolean;
  isDefaultPtrContract: boolean;
  documents: util.DocItem[];
  notes: string
  productId: number;
}

export interface RequiredData {
  hasModifyPermission: boolean;
  pipelines: Pipeline[];
  zones: Zone[];
  meters: Meter[];
  contractTypes: util.IdName[];
  rateSchedules: RateSchedule[];
  rateUnits: util.IdName[];
  products: util.IdName[];
  counterparties: util.IdName[];
}

export interface RateSchedule {
  id: number;
  name: string;
  pipelineId: number;
  contractType: number;
  productId: number;
}

export interface Pipeline {
  pipeId: number;
  pipeName: string;
  isCrudePipe: boolean;
  isGasPipe: boolean;
  productIds: number[];
}

export interface Zone {
  id: number;
  name: string;
  pipelineId: number;
}

export interface Meter {
  meterId: number;
  meterName: string;
  meterNum: number;
  zoneId: number;
  pipeId: number;
}

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

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

  getItems(state: State): Observable<GridDataResult> {
    return this.fetch(`GetPipeContractItems`, 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: util.SaveType): Observable<number> {
    const url = `${this.baseUrl}/SaveDetail?saveType=${saveType}`;
    detail = util.convertDatesToDateOnlyStrings(detail, ["startDate", "endDate"]);
    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(`GetPipeContractItems`, state, null, fileNameOriginal);
  }

  downloadDoc(fileNameOriginal: string, fileNameOnDisk: string): Observable<{ fileBlob: Blob, fileName: string }> {
    const url = `${this.baseUrl}/DownloadDoc?fileNameOnDisk=${fileNameOnDisk}`;
    return this.http.get(url, { observe: 'response', responseType: 'blob' }).pipe(
      map(result => {
        const fileBlob = result.body;
        const fileName: string = result.body.type === "text/plain" ? "Error.txt" : fileNameOriginal;
        return { fileBlob, fileName };
      })
    );
  }
}
