import $ from 'jquery'
import 'core-js/fn/array/find'

export class StatsSourceCollector {
  constructor ({id, metrics, methods}) {
    this.id = id
    this.metrics = metrics
    this.methods = methods
  }

  static get Source () {
    throw new Error('It should implement getter in subclasses.')
  }

  getSources () {
    throw new Error('It should implement getSources method in subclasses.')
  }

  get url () {
    throw new Error('It should implement url getter in subclasses.')
  }

  params ({dateRange, selectedMetricName}) {
    return {
      metric_name: selectedMetricName,
      granularity: dateRange.granularity,
      since: dateRange.since,
      until: dateRange.until,
      skip_change: true
    }
  }

  getMetricDetails (selectedMetricName) {
    let selectedMetric = this.metrics.find(metric => metric.systemName === selectedMetricName)
    return (selectedMetricName === 'hits' && this.methods.length > 0)
      ? [selectedMetric, ...this.methods]
      : [selectedMetric]
  }

  buildSources (id, selectedMetricName) {
    let metricDetails = this.getMetricDetails(selectedMetricName)
    const Source = Object.getPrototypeOf(this).constructor.Source
    return metricDetails.map(metricDetails => new Source({id, details: metricDetails}))
  }

  _sourcesRequest (options) {
    return new Promise((resolve, reject) => {
      this.request = $.getJSON(this.url, this.params(options))
        .then(response => resolve(response))
        .fail((xhr, status, error) => reject(`Request failed: ${status}, ${error}`))
    })
  }
}
