import Ember from 'ember'
export default Ember.Controller.extend
  grouped_tracker_groups: Ember.A()
  uncategorized_workflow_groups: Ember.A()
  #grouped_tracker_groups: Ember.computed.alias("model.tracker_subject.sorted_tracker_groups")

  #grouped_tracker_groups_setter: (->
  #  base = @
  #  group = Ember.A()
  #  project_workflow_groups = @get('model.project.workflow_groups')
  #  @get("model.tracker_subject.tracker_groups").then (tracker_groups)->
  #    tracker_groups.forEach (tracker_group)->
  #      item_group = Ember.Object.extend(
  #        workflow_groups: Ember.computed.intersect("model.workflow_groups", "project_workflow_groups")
  #      ).create
  #        model: tracker_group
  #        project_workflow_groups: project_workflow_groups
  #      c = base
  #      debugger
  #      #item_group = Ember.Object.create
  #      #  model: tracker_group
  #      #  workflow_groups: workflow_groups.filterBy("")
  #      #tracker_group.get('workflow_groups').then (workflow_groups)->
  #      #  workflow_groups.forEach (workflow_group)->
  #      #    hasProject = existing_project_group = item_group.get("projects").findBy("model.id", workflow_group.get("project.id"))
  #      #    if hasProject
  #      #      existing_project_group.get("workflow_groups").push(workflow_group)
  #      #    else
  #      #      item_group.get("projects").pushObject Ember.Object.create(model: workflow_group.get('project'), workflow_groups: Ember.A([workflow_group]))
  #      #    base.incrementProperty "change_iteration"
  #      group.push item_group
  #  @set("grouped_tracker_groups", group)
  #).observes  "model.tracker_subject.tracker_groups.@each.workflow_groups.[]"

  grouped_tracker_groups_setter: (->
    base = @
    group = Ember.A()
    tracker_subject_id = @get("model.tracker_subject.id")
    categorized_workflow_group_ids = []
    @get("model.tracker_subject.tracker_groups").forEach (tracker_group) ->
      group.pushObject
        model: tracker_group
        workflow_groups: Ember.A()

    @get('model.project.workflow_groups').forEach (workflow_group)->
      return unless project_tracker_group = workflow_group.get('tracker_groups').findBy("tracker_subject.id", tracker_subject_id)
      return unless item_group = group.findBy("model.id", project_tracker_group.id)
      categorized_workflow_group_ids.push workflow_group.id
      item_group.workflow_groups.pushObject workflow_group
      item_group.workflow_groups = item_group.workflow_groups.sortBy("position")
    @set("grouped_tracker_groups", group)
    uncategorized_workflow_groups = @get('model.project.workflow_groups').reject((ws) -> categorized_workflow_group_ids.includes(ws.id))
    @set("uncategorized_workflow_groups", uncategorized_workflow_groups.sortBy("position"))
  ).observes  "model.project.workflow_groups.@each.tracker_groups.[]", "model.tracker_subject.tracker_groups.[]"
