import * as helpers from './stats_helpers'
import {StatsSourceCollector} from './source_collector'
import {StatsTopApplicationMetricsSource} from './top_application_metrics_source'

export class StatsTopAppsSourceCollector extends StatsSourceCollector {
  static get Source () {
    return StatsTopApplicationMetricsSource
  }

  get url () {
    return `/stats/services/${this.id}/top_applications.json`
  }

  params ({dateRange, selectedMetricName}) {
    return Object.assign({},
      super.params({dateRange, selectedMetricName}),
      {period: helpers.getPeriodFromDateRange(dateRange)}
    )
  }

  getSources (options) {
    return this._sourcesRequest(options).then(response => this.buildSources(response, options.selectedMetricName))
  }

  getMetricDetails (selectedMetricName) {
    return [this.metrics.find(metric => metric.systemName === selectedMetricName)]
  }

  buildSources (sources, selectedMetricName) {
    return sources.applications.map(source => {
      return this._addSelectionPeriodToSource(super.buildSources(source.id, selectedMetricName)[0], sources.period)
    })
  }

  _addSelectionPeriodToSource (source, period) {
    source.topAppsSelectionPeriod = period
    return source
  }
}
