export class CurrenciesLoader {
  public onData?: (currencies: Currencies) => void = undefined
  private updateTime: number = 86400000
  private updateTimer?: number = undefined
  private currencies: Currencies = {}

  private setUpdateTime(miliseconds?: number) {
    window.clearTimeout(this.updateTimer)
    if (miliseconds === undefined) return

    this.updateTimer = window.setTimeout(this.requestCurrencies, miliseconds)
  }

  private dispatchData(currencies: Currencies) {
    this.onData?.(currencies)
  }

  private readonly requestCurrencies = () => {
    window.clearTimeout(this.updateTimer)
    const currencies: Currencies = {}

    if (this.currencies && typeof this.currencies === 'object' && !Array.isArray(this.currencies)) {
      Object.assign(currencies, this.currencies)
    }

    if (Object.keys(currencies).length > 0) this.dispatchData(currencies)

    this.setUpdateTime(this.updateTime > 10000 ? this.updateTime : 10000)
  }

  update(appData: VixonicData) {
    const serviceId = appData?.parameters?.currencyService?.id
    if (!serviceId) return

    const serviceData = appData?.services?.[serviceId]?.data?.currencies
    this.currencies = serviceData
    this.updateTime = 86400000
    this.requestCurrencies()
  }

  stop() {
    this.setUpdateTime()
  }
}
