import { getAssetUrl } from '@/api/asset'
import { getProgram as programApi } from '@/api/program'
import { getSchedule as scheduleApi } from '@/api/calendar'
import { EventTarget } from '@/constant'

const cacheMap = {}

function getProgramInst (id) {
  return programApi(id, { custom: true, background: true }).then(({ data }) => data)
}

function getScheduleInst (id) {
  return scheduleApi(id, { custom: true, background: true })
}

function getProgramImage ({ img }) {
  return getAssetUrl(img)
}

function getScheduleImage ({ events }) {
  return getImage(EventTarget.PROGRAM, events[0].programId)
}

function getCache (type) {
  if (!cacheMap[type]) {
    cacheMap[type] = {}
  }
  return cacheMap[type]
}

function getPromise (type, id) {
  const key = `${type}__${id}`
  const cache = getCache()
  if (!cache[key]) {
    const promise = (type === EventTarget.PROGRAM ? getProgramInst : getScheduleInst)(id)
    promise.catch(() => {
      cache[key] = null
    })
    cache[key] = promise
  }
  return cache[key]
}

export function getImage (type, id) {
  return getPromise(type, id).then(type === EventTarget.PROGRAM ? getProgramImage : getScheduleImage)
}
