import { AnniversaryServiceParsers } from './service-parsers'

export class AnniversaryLoader {
  public onData?: (birthdays: Anniversary[]) => void = undefined
  private updateTime: number = 86400000
  private updateTimer?: number = undefined
  private anniversariesData: Anniversary[] = []
  private serviceType: VixonicData['parameters']['displayService'] = 'AnniversaryAppService'

  private getServiceType(appData: VixonicData) {
    switch (appData.parameters.displayService) {
      case 'RexmasAnniversarieService':
        return appData.parameters.rexmasService?.id
      case 'BukAnniversarieService':
        return appData.parameters.bukService?.id
      case 'TalanaAnniversariesService':
        return appData.parameters.talanaService?.id
      default:
        return appData.parameters.documentService?.id
    }
  }

  update(appData: VixonicData) {
    const selectedServiceId = this.getServiceType(appData)
    if (!selectedServiceId || !appData.services[selectedServiceId]) return
    const serviceData = appData.services[selectedServiceId].data as Anniversary[] | undefined

    const serviceTypeName = appData.parameters.displayService

    this.serviceType = serviceTypeName ?? 'AnniversaryAppService'

    if (Array.isArray(serviceData)) {
      const parser = AnniversaryServiceParsers.getParser(this.serviceType)
      this.anniversariesData = parser.parse(serviceData)
    } else {
      this.anniversariesData = []
    }

    this.updateTime = appData.parameters.updateTime ?? 86400000
    this.requestBirthdays()
  }

  stop() {
    this.setUpdateTime(undefined)
  }

  private setUpdateTime(milliseconds?: number) {
    window.clearTimeout(this.updateTimer)
    if (!milliseconds) return
    this.updateTimer = window.setTimeout(this.requestBirthdays, milliseconds)
  }

  private dispatchData(anniversaries: Anniversary[]) {
    this.onData?.(anniversaries)
  }

  private readonly requestBirthdays = () => {
    window.clearTimeout(this.updateTimer)
    const birthdays: Anniversary[] = []

    if (Array.isArray(this.anniversariesData)) {
      this.anniversariesData.forEach((item) => {
        birthdays.push(item)
      })
    }

    if (birthdays.length > 0) this.dispatchData(birthdays)

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