import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";
import {map} from "rxjs/operators";
import * as moment from 'moment'
import * as _ from 'underscore'

@Injectable({providedIn: "root"})
export class AccountService {

  constructor(private httpClient: HttpClient) {

  }

  getAccountsInfo(personId: string): Observable<AccountInfo[]> {
    return this.httpClient.get(`/api/old/person/${personId}/accounts`).pipe(map((res: any) => <AccountInfo[]>res.accounts))
  }

  addAccount(personId: string): Observable<string> {
    return this.httpClient.post(`/api/old/person/${personId}/accounts/add`, {}).pipe(map((res: any) => <string>res.id))
  }

  getAccountEvents(personId: string): Observable<AccountEvent[]> {
    return this.httpClient.get(`/api/old/person/${personId}/events`).pipe(map((res: any[]) => res.map(e => {
      let ev = new AccountEvent()
      ev.date = moment(e.ts).toDate()
      ev.type = _.last(e.type.split("."))
      ev.id = e.id
      switch (ev.type) {
        case "ExchangeSuccessEvent":
          ev.info = e.info.parentEvent
          break;
        case "ExchangeFailedEvent":
          ev.info = e.info.parentEvent
          break;
        default:
          throw new Error(`unknown event ${e.type}`)
      }
      return ev
    })))
  }
}

export class AccountInfo {
  id: string
  overall: number
}

export class AccountEvent {
  id: string
  type: string
  date: Date
  info: any
}
