/**
 * 数据源的基类
 */
import util from '../libs/util'
import {normalizeUrl} from '../libs/base_url'
class Source {
  constructor(id, specification, eventParent) {
    this.id = id
    this.eventParent = eventParent
    clearInterval(this.timer)
    if (specification.transform) {
      this.transform = specification.transform
    }
    if (specification.url) {
      //API数据
      this.frequency = specification.frequency || 0 //定时刷新，0为不刷新
      this.proxy = specification.proxy || false //是否设置代理
      this.getUrlData(specification.url)
      if (this.frequency) {
        this.timer = setInterval(() => {
          this.getUrlData(specification.url, true)
        }, this.frequency * 1000)
      }
    } else if (specification.data) {
      //静态数据
      setTimeout(() => {
        this.reduceData(specification.data)
      }, 0)
    } else {
      setTimeout(() => {
        this.eventParent.fire('source.load', { id: this.id, data: null })
      }, 0)
    }
  }

  async getUrlData(url, cache) {
    url = normalizeUrl(url)
    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]}`
      }
    }
    if (cache) {
      newUrl += `&_t=${new Date().getTime()}`
    }
    let data = []
    try {
      let res = await fetch(newUrl)
      data = await res.json()
    } catch (err) {
      throw new Error(`Error in component "${this.id}": Fetch data faild`)
    }
    this.reduceData(data)
  }

  destroy() {
    clearInterval(this.timer)
  }
}

export default Source
