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 {
  BrokerId: number;
  BrokerName: string;
  BrokerType: string;
  BrokerAccounts: string;
  CommissionPerContract: number;
  CommissionAfterHours: number;
  CommissionForEFS: number;
  Memo: string;
}

export interface Detail {
  brokerId: number;
  brokerName: string;
  brokerType: string;
  brokerAccounts: util.IdName[];
  commissionPerContract: number;
  commissionAfterHours: number;
  commissionForEFS: number;
  memo: string;
}

export interface BrokerAccountItem {
  id: number;
  name: string;
}

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

export interface RequiredData {
  hasModifyPermission: boolean;
  brokerTypes: { brokerType: string }[];
  brokerAccounts: util.IdName[];
}

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

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

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

  addNewBrokerAccount(brokerId: number, brokerAccountName: string) {
    const url = `${this.baseUrl}/AddNewBrokerAccount/${brokerId}/${brokerAccountName}`;
    return this.http.post(url, null);
  };

  renameBrokerAccount(brokerId: number, brokerAccountName: string) {
    const url = `${this.baseUrl}/RenameBrokerAccount/${brokerId}/${brokerAccountName}`;
    return this.http.put(url, null);
  };

  deleteBrokerAccount(brokerId: number) {
    const url = `${this.baseUrl}/DeleteBrokerAccount/${brokerId}`;
    return this.http.delete(url);
  };
}
