import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { SosDeal, SosTransferAdd, SosTransferPath, SosTransferPathDeals } from '../models';
import { Observable } from 'rxjs';
import dayjs from 'dayjs';
import * as util from '../../_shared/utils/util';

export interface SosSettingItem {
  pipeId: number;
  fontSize: number;
  frozenColumnCount: number;
  displayInfos: DisplayInfo[];
}

export interface DisplayInfo {
  propName: string;
  displayName: string;
  width: number;
  order: number;
}

export enum SaveType {
  supply,
  market,
  transfer
}

export interface AddDealParams {
  selectedDrawerText: string;
  supplyCounterpartyId: number;
  supplyDealType: string;
  receiptPointId: number;
  marketCounterpartyId: number;
  marketDealType: string;
  transferSourceMeterId: number;
  transferSourceCounterpartyId: number;
  sourceTicket: string;
}

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

  saveSuplyDeal(supplyItem: SosDeal): Observable<object> {
    const url = `${this.baseUrl}/SaveSupplyDeal`;
    supplyItem = util.convertDatesToDateOnlyStrings(supplyItem, ["startDate", "endDate"]);
    return this.http.put<object>(url, supplyItem);
  }

  saveMarketDeal(marketItem: SosDeal): Observable<object> {
    const url = `${this.baseUrl}/SaveMarketDeal`;
    marketItem = util.convertDatesToDateOnlyStrings(marketItem, ["startDate", "endDate"]);
    return this.http.put<object>(url, marketItem);
  }

  saveTransferDeal(transferItem: SosTransferAdd): Observable<object> {
    const url = `${this.baseUrl}/SaveTransfer`;
    transferItem = util.convertDatesToDateOnlyStrings(transferItem, ["startDate", "endDate"]);
    return this.http.put<object>(url, transferItem);
  }

  getTransferPaths(pipeId: number): Observable<SosTransferPath[]> {
    const url = `${this.baseUrl}/GetTransferPaths?pipeId=${pipeId}`;
    return this.http.get<SosTransferPath[]>(url);
  }

  getTransferDeals(pathId: number, meterId: number, nomDate: Date): Observable<SosTransferPathDeals> {
    const nomDateStr = dayjs(nomDate).format("YYYY-MM-DD");
    const url = `${this.baseUrl}/GetTransferDeals?pathId=${pathId}&meterId=${meterId}&nomDate=${nomDateStr}`;
    return this.http.get<SosTransferPathDeals>(url);
  }
}
