import Ember from 'ember'
import DS from 'ember-data'

export default Ember.Component.extend
  record: null # parameter
  project_specific: false # parameter
  session: Ember.inject.service('session')
  classNames: ['project-aggregate-statistics', 'project-aggregate-organization-statistics']
  statistics: Ember.computed 'statistics_data.isFulfilled', 'project_specific', ->
    d = @get('statistics_data')
    return {} unless d.isFulfilled
    target = {}
    states = ['pending', 'planned', 'active', 'overdue', 'inquiry', 'rejected', 'completed']
    project_specific = @get('project_specific')
    unless project_specific
      states.forEach (state) ->
        target[state] = 0
    for project_id, stats of d.content.data
      if project_specific
        project = d.content.projects.findBy('id', project_id)
        target[project_id] = {project: project, states: []}
        states.forEach (state) ->
          target[project_id].states.push(state: state, count: stats[state] || 0)
      else
        for state, count of stats
          target[state] += count

      #if project_object.project and project_object.project.id isnt project.id
      #  target.push project_object
      #  project_object = {project: project}
      #  continue
      #project_object.project = project

    target

  statistics_data: Ember.computed ->
    return {} unless record_id = @get('record.id')
    model_name = 'panda/organization'
    base_url = @store.adapterFor(model_name).buildURL(model_name)
    url = "#{base_url}/#{record_id}/statistics1"
    session = @get('session')
    store = @store
    request =
      url: url
      contentType: "application/json"
      dataType: "json"
      #success: (response) ->
      #  resolve(response)
    if Ember.get(session, 'isAuthenticated')
      session.authorize 'authorizer:devise', (key, authorization) ->
        request.crossDomain = true
        request.headers = {"#{key}": authorization}
    DS.PromiseObject.create
      promise: Ember.RSVP.hash(data: Ember.$.ajax(request), projects: store.findAll('panda/project', backgroundReload: false))
