/**
 * 数据源的基类
 */
import util from './libs/util'
class Source {
  constructor(id, specification, eventParent) {
    this.id = id
    this.eventParent = eventParent
    if (specification.url) {
      //API数据
      this.getUrlData(specification.url, specification.type)
    } else if (specification.data) {
      //静态数据
      this.eventParent.fire('source.load', {
        id: this.id,
        data: specification.data
      })
    } else {
      this.eventParent.fire('source.load', { id: this.id, data: null })
    }
  }

  async getUrlData(url, type) {
    if (type === 'image') {
      // 图片数据
      this.eventParent.fire('source.load', { id: this.id, data: url })
      return
    }
    let parser = util.parseUrl(url)
    let newUrl = `${parser.protocol}//${parser.host}${parser.pathname}?`
    for (let key in parser.query) {
      // 过滤掉值为空的参数
      if (parser.query[key] !== '') {
        newUrl += `&${key}=${parser.query[key]}`
      }
    }
    let data = []
    try {
      let res = await fetch(newUrl)
      if (type === 'csv') {
        data = await res.text()
      } else {
        data = await res.json()
      }
    } catch (err) {
      throw new Error(`Error in component "${this.id}": Fetch data faild`)
    }
    this.eventParent.fire('source.load', { id: this.id, data })
  }
}

export default Source
